/*----------------------------------------------------------------------------/
/  FatFs - FAT file system module  R0.09b                 (C)ChaN, 2013
/-----------------------------------------------------------------------------/
/ FatFs module is a generic FAT file system module for small embedded systems.
/ This is a free software that opened for education, research and commercial
/ developments under license policy of following terms.
/
/  Copyright (C) 2013, ChaN, all right reserved.
/
/ * The FatFs module is a free software and there is NO WARRANTY.
/ * No restriction on use. You can use, modify and redistribute it for
/   personal, non-profit or commercial products UNDER YOUR RESPONSIBILITY.
/ * Redistributions of source code must retain the above copyright notice.
/
/-----------------------------------------------------------------------------/
/ Feb 26,'06 R0.00  Prototype.
/
/ Apr 29,'06 R0.01  First stable version.
/
/ Jun 01,'06 R0.02  Added FAT12 support.
/                   Removed unbuffered mode.
/                   Fixed a problem on small (<32M) partition.
/ Jun 10,'06 R0.02a Added a configuration option (_FS_MINIMUM).
/
/ Sep 22,'06 R0.03  Added f_rename().
/                   Changed option _FS_MINIMUM to _FS_MINIMIZE.
/ Dec 11,'06 R0.03a Improved cluster scan algorithm to write files fast.
/                   Fixed f_mkdir() creates incorrect directory on FAT32.
/
/ Feb 04,'07 R0.04  Supported multiple drive system.
/                   Changed some interfaces for multiple drive system.
/                   Changed f_mountdrv() to f_mount().
/                   Added f_mkfs().
/ Apr 01,'07 R0.04a Supported multiple partitions on a physical drive.
/                   Added a capability of extending file size to f_lseek().
/                   Added minimization level 3.
/                   Fixed an endian sensitive code in f_mkfs().
/ May 05,'07 R0.04b Added a configuration option _USE_NTFLAG.
/                   Added FSInfo support.
/                   Fixed DBCS name can result FR_INVALID_NAME.
/                   Fixed short seek (<= csize) collapses the file object.
/
/ Aug 25,'07 R0.05  Changed arguments of f_read(), f_write() and f_mkfs().
/                   Fixed f_mkfs() on FAT32 creates incorrect FSInfo.
/                   Fixed f_mkdir() on FAT32 creates incorrect directory.
/ Feb 03,'08 R0.05a Added f_truncate() and f_utime().
/                   Fixed off by one error at FAT sub-type determination.
/                   Fixed btr in f_read() can be mistruncated.
/                   Fixed cached sector is not flushed when create and close without write.
/
/ Apr 01,'08 R0.06  Added fputc(), fputs(), fprintf() and fgets().
/                   Improved performance of f_lseek() on moving to the same or following cluster.
/
/ Apr 01,'09 R0.07  Merged Tiny-FatFs as a configuration option. (_FS_TINY)
/                   Added long file name feature.
/                   Added multiple code page feature.
/                   Added re-entrancy for multitask operation.
/                   Added auto cluster size selection to f_mkfs().
/                   Added rewind option to f_readdir().
/                   Changed result code of critical errors.
/                   Renamed string functions to avoid name collision.
/ Apr 14,'09 R0.07a Separated out OS dependent code on reentrant cfg.
/                   Added multiple sector size feature.
/ Jun 21,'09 R0.07c Fixed f_unlink() can return FR_OK on error.
/                   Fixed wrong cache control in f_lseek().
/                   Added relative path feature.
/                   Added f_chdir() and f_chdrive().
/                   Added proper case conversion to extended char.
/ Nov 03,'09 R0.07e Separated out configuration options from ff.h to ffconf.h.
/                   Fixed f_unlink() fails to remove a sub-dir on _FS_RPATH.
/                   Fixed name matching error on the 13 char boundary.
/                   Added a configuration option, _LFN_UNICODE.
/                   Changed f_readdir() to return the SFN with always upper case on non-LFN cfg.
/
/ May 15,'10 R0.08  Added a memory configuration option. (_USE_LFN = 3)
/                   Added file lock feature. (_FS_SHARE)
/                   Added fast seek feature. (_USE_FASTSEEK)
/                   Changed some types on the API, XCHAR->TCHAR.
/                   Changed fname member in the FILINFO structure on Unicode cfg.
/                   String functions support UTF-8 encoding files on Unicode cfg.
/ Aug 16,'10 R0.08a Added f_getcwd(). (_FS_RPATH = 2)
/                   Added sector erase feature. (_USE_ERASE)
/                   Moved file lock semaphore table from fs object to the bss.
/                   Fixed a wrong directory entry is created on non-LFN cfg when the given name contains ';'.
/                   Fixed f_mkfs() creates wrong FAT32 volume.
/ Jan 15,'11 R0.08b Fast seek feature is also applied to f_read() and f_write().
/                   f_lseek() reports required table size on creating CLMP.
/                   Extended format syntax of f_printf function.
/                   Ignores duplicated directory separators in given path name.
/
/ Sep 06,'11 R0.09  f_mkfs() supports multiple partition to finish the multiple partition feature.
/                   Added f_fdisk(). (_MULTI_PARTITION = 2)
/ Aug 27,'12 R0.09a Fixed assertion failure due to OS/2 EA on FAT12/16 volume.
/                   Changed f_open() and f_opendir reject null object pointer to avoid crash.
/                   Changed option name _FS_SHARE to _FS_LOCK.
/ Jan 24,'13 R0.09b Added f_setlabel() and f_getlabel(). (_USE_LABEL = 1)
/---------------------------------------------------------------------------*/

#include "ff.h"			/* FatFs configurations and declarations */
#include "diskio.h"		/* Declarations of low level disk I/O functions */


#ifdef DEBUG
#include <stdio.h>
#include "print_debug.h"
#include "config_debug.h"

#if DEBUG_FATFS
static char _buf_dbg[100];
#define FATFS_DEBUGF(...)	do {	\
	snprintf(_buf_dbg, 100, __VA_ARGS__); \
	print_dbg((const char*)_buf_dbg);	\
}while(0);
#else
#define FATFS_DEBUGF(...)
#endif /* DEBUG_FATFS */
#endif /* DEBUG */


/*--------------------------------------------------------------------------

   Module Private Definitions

---------------------------------------------------------------------------*/

#if _FATFS != 82786	/* Revision ID */
#error Wrong include file (ff.h).
#endif


/* Definitions on sector size */
#if _MAX_SS != 512 && _MAX_SS != 1024 && _MAX_SS != 2048 && _MAX_SS != 4096
#error Wrong sector size.
#endif
#if _MAX_SS != 512
#define	SS(_fs)	((_fs)->ssize)	/* Variable sector size */
#else
#define	SS(_fs)	512U			/* Fixed sector size */
#endif


/* Reentrancy related */
#if _FS_REENTRANT
#if _USE_LFN == 1
#error Static LFN work area must not be used in re-entrant configuration.
#endif
#define	ENTER_FF(_fs)		{ if (!lock_fs(_fs)) return FR_TIMEOUT; }
#define	LEAVE_FF(_fs, _res)	{ unlock_fs(_fs, _res); return _res; }
#else
#define	ENTER_FF(_fs)
#define LEAVE_FF(_fs, _res)	return _res
#endif

#define	ABORT(_fs, _res)		{ _fp->flag |= FA__ERROR; LEAVE_FF(_fs, _res); }


/* File access control feature */
#if _FS_LOCK
#if _FS_READONLY
#error _FS_LOCK must be 0 on read-only cfg.
#endif
typedef struct {
	FATFS *fs;				/* File ID 1, volume (NULL:blank entry) */
	DWORD clu;				/* File ID 2, directory */
	WORD idx;				/* File ID 3, directory index */
	WORD ctr;				/* File open counter, 0:none, 0x01..0xFF:read open count, 0x100:write mode */
} FILESEM;
#endif



/* DBCS code ranges and SBCS extend char conversion table */

#if _CODE_PAGE == 932	/* Japanese Shift-JIS */
#define _DF1S	0x81	/* DBC 1st byte range 1 start */
#define _DF1E	0x9F	/* DBC 1st byte range 1 end */
#define _DF2S	0xE0	/* DBC 1st byte range 2 start */
#define _DF2E	0xFC	/* DBC 1st byte range 2 end */
#define _DS1S	0x40	/* DBC 2nd byte range 1 start */
#define _DS1E	0x7E	/* DBC 2nd byte range 1 end */
#define _DS2S	0x80	/* DBC 2nd byte range 2 start */
#define _DS2E	0xFC	/* DBC 2nd byte range 2 end */

#elif _CODE_PAGE == 936	/* Simplified Chinese GBK */
#define _DF1S	0x81
#define _DF1E	0xFE
#define _DS1S	0x40
#define _DS1E	0x7E
#define _DS2S	0x80
#define _DS2E	0xFE

#elif _CODE_PAGE == 949	/* Korean */
#define _DF1S	0x81
#define _DF1E	0xFE
#define _DS1S	0x41
#define _DS1E	0x5A
#define _DS2S	0x61
#define _DS2E	0x7A
#define _DS3S	0x81
#define _DS3E	0xFE

#elif _CODE_PAGE == 950	/* Traditional Chinese Big5 */
#define _DF1S	0x81
#define _DF1E	0xFE
#define _DS1S	0x40
#define _DS1E	0x7E
#define _DS2S	0xA1
#define _DS2E	0xFE

#elif _CODE_PAGE == 437	/* U.S. (OEM) */
#define _DF1S	0
#define _EXCVT {0x80,0x9A,0x90,0x41,0x8E,0x41,0x8F,0x80,0x45,0x45,0x45,0x49,0x49,0x49,0x8E,0x8F,0x90,0x92,0x92,0x4F,0x99,0x4F,0x55,0x55,0x59,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
				0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0x21,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
				0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
				0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}

#elif _CODE_PAGE == 720	/* Arabic (OEM) */
#define _DF1S	0
#define _EXCVT {0x80,0x81,0x45,0x41,0x84,0x41,0x86,0x43,0x45,0x45,0x45,0x49,0x49,0x8D,0x8E,0x8F,0x90,0x92,0x92,0x93,0x94,0x95,0x49,0x49,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
				0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
				0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
				0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}

#elif _CODE_PAGE == 737	/* Greek (OEM) */
#define _DF1S	0
#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x92,0x92,0x93,0x94,0x95,0x96,0x97,0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87, \
				0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0xAA,0x92,0x93,0x94,0x95,0x96,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
				0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
				0x97,0xEA,0xEB,0xEC,0xE4,0xED,0xEE,0xE7,0xE8,0xF1,0xEA,0xEB,0xEC,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}

#elif _CODE_PAGE == 775	/* Baltic (OEM) */
#define _DF1S	0
#define _EXCVT {0x80,0x9A,0x91,0xA0,0x8E,0x95,0x8F,0x80,0xAD,0xED,0x8A,0x8A,0xA1,0x8D,0x8E,0x8F,0x90,0x92,0x92,0xE2,0x99,0x95,0x96,0x97,0x97,0x99,0x9A,0x9D,0x9C,0x9D,0x9E,0x9F, \
				0xA0,0xA1,0xE0,0xA3,0xA3,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
				0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xB5,0xB6,0xB7,0xB8,0xBD,0xBE,0xC6,0xC7,0xA5,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
				0xE0,0xE1,0xE2,0xE3,0xE5,0xE5,0xE6,0xE3,0xE8,0xE8,0xEA,0xEA,0xEE,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}

#elif _CODE_PAGE == 850	/* Multilingual Latin 1 (OEM) */
#define _DF1S	0
#define _EXCVT {0x80,0x9A,0x90,0xB6,0x8E,0xB7,0x8F,0x80,0xD2,0xD3,0xD4,0xD8,0xD7,0xDE,0x8E,0x8F,0x90,0x92,0x92,0xE2,0x99,0xE3,0xEA,0xEB,0x59,0x99,0x9A,0x9D,0x9C,0x9D,0x9E,0x9F, \
				0xB5,0xD6,0xE0,0xE9,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0x21,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
				0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC7,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
				0xE0,0xE1,0xE2,0xE3,0xE5,0xE5,0xE6,0xE7,0xE7,0xE9,0xEA,0xEB,0xED,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}

#elif _CODE_PAGE == 852	/* Latin 2 (OEM) */
#define _DF1S	0
#define _EXCVT {0x80,0x9A,0x90,0xB6,0x8E,0xDE,0x8F,0x80,0x9D,0xD3,0x8A,0x8A,0xD7,0x8D,0x8E,0x8F,0x90,0x91,0x91,0xE2,0x99,0x95,0x95,0x97,0x97,0x99,0x9A,0x9B,0x9B,0x9D,0x9E,0x9F, \
				0xB5,0xD6,0xE0,0xE9,0xA4,0xA4,0xA6,0xA6,0xA8,0xA8,0xAA,0x8D,0xAC,0xB8,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBD,0xBF, \
				0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC6,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD1,0xD1,0xD2,0xD3,0xD2,0xD5,0xD6,0xD7,0xB7,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
				0xE0,0xE1,0xE2,0xE3,0xE3,0xD5,0xE6,0xE6,0xE8,0xE9,0xE8,0xEB,0xED,0xED,0xDD,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xEB,0xFC,0xFC,0xFE,0xFF}

#elif _CODE_PAGE == 855	/* Cyrillic (OEM) */
#define _DF1S	0
#define _EXCVT {0x81,0x81,0x83,0x83,0x85,0x85,0x87,0x87,0x89,0x89,0x8B,0x8B,0x8D,0x8D,0x8F,0x8F,0x91,0x91,0x93,0x93,0x95,0x95,0x97,0x97,0x99,0x99,0x9B,0x9B,0x9D,0x9D,0x9F,0x9F, \
				0xA1,0xA1,0xA3,0xA3,0xA5,0xA5,0xA7,0xA7,0xA9,0xA9,0xAB,0xAB,0xAD,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB6,0xB6,0xB8,0xB8,0xB9,0xBA,0xBB,0xBC,0xBE,0xBE,0xBF, \
				0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC7,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD1,0xD1,0xD3,0xD3,0xD5,0xD5,0xD7,0xD7,0xDD,0xD9,0xDA,0xDB,0xDC,0xDD,0xE0,0xDF, \
				0xE0,0xE2,0xE2,0xE4,0xE4,0xE6,0xE6,0xE8,0xE8,0xEA,0xEA,0xEC,0xEC,0xEE,0xEE,0xEF,0xF0,0xF2,0xF2,0xF4,0xF4,0xF6,0xF6,0xF8,0xF8,0xFA,0xFA,0xFC,0xFC,0xFD,0xFE,0xFF}

#elif _CODE_PAGE == 857	/* Turkish (OEM) */
#define _DF1S	0
#define _EXCVT {0x80,0x9A,0x90,0xB6,0x8E,0xB7,0x8F,0x80,0xD2,0xD3,0xD4,0xD8,0xD7,0x98,0x8E,0x8F,0x90,0x92,0x92,0xE2,0x99,0xE3,0xEA,0xEB,0x98,0x99,0x9A,0x9D,0x9C,0x9D,0x9E,0x9E, \
				0xB5,0xD6,0xE0,0xE9,0xA5,0xA5,0xA6,0xA6,0xA8,0xA9,0xAA,0xAB,0xAC,0x21,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
				0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC7,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
				0xE0,0xE1,0xE2,0xE3,0xE5,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xDE,0x59,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}

#elif _CODE_PAGE == 858	/* Multilingual Latin 1 + Euro (OEM) */
#define _DF1S	0
#define _EXCVT {0x80,0x9A,0x90,0xB6,0x8E,0xB7,0x8F,0x80,0xD2,0xD3,0xD4,0xD8,0xD7,0xDE,0x8E,0x8F,0x90,0x92,0x92,0xE2,0x99,0xE3,0xEA,0xEB,0x59,0x99,0x9A,0x9D,0x9C,0x9D,0x9E,0x9F, \
				0xB5,0xD6,0xE0,0xE9,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0x21,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
				0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC7,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD1,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
				0xE0,0xE1,0xE2,0xE3,0xE5,0xE5,0xE6,0xE7,0xE7,0xE9,0xEA,0xEB,0xED,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}

#elif _CODE_PAGE == 862	/* Hebrew (OEM) */
#define _DF1S	0
#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
				0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0x21,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
				0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
				0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}

#elif _CODE_PAGE == 866	/* Russian (OEM) */
#define _DF1S	0
#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
				0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
				0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
				0x90,0x91,0x92,0x93,0x9d,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F,0xF0,0xF0,0xF2,0xF2,0xF4,0xF4,0xF6,0xF6,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}

#elif _CODE_PAGE == 874	/* Thai (OEM, Windows) */
#define _DF1S	0
#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
				0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
				0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
				0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}

#elif _CODE_PAGE == 1250 /* Central Europe (Windows) */
#define _DF1S	0
#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x8A,0x9B,0x8C,0x8D,0x8E,0x8F, \
				0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xA3,0xB4,0xB5,0xB6,0xB7,0xB8,0xA5,0xAA,0xBB,0xBC,0xBD,0xBC,0xAF, \
				0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
				0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xF7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xFF}

#elif _CODE_PAGE == 1251 /* Cyrillic (Windows) */
#define _DF1S	0
#define _EXCVT {0x80,0x81,0x82,0x82,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x80,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x8A,0x9B,0x8C,0x8D,0x8E,0x8F, \
				0xA0,0xA2,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB2,0xA5,0xB5,0xB6,0xB7,0xA8,0xB9,0xAA,0xBB,0xA3,0xBD,0xBD,0xAF, \
				0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
				0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF}

#elif _CODE_PAGE == 1252 /* Latin 1 (Windows) */
#define _DF1S	0
#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0xAd,0x9B,0x8C,0x9D,0xAE,0x9F, \
				0xA0,0x21,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
				0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
				0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xF7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0x9F}

#elif _CODE_PAGE == 1253 /* Greek (Windows) */
#define _DF1S	0
#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
				0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
				0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xA2,0xB8,0xB9,0xBA, \
				0xE0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xF2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xFB,0xBC,0xFD,0xBF,0xFF}

#elif _CODE_PAGE == 1254 /* Turkish (Windows) */
#define _DF1S	0
#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x8A,0x9B,0x8C,0x9D,0x9E,0x9F, \
				0xA0,0x21,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
				0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
				0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xF7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0x9F}

#elif _CODE_PAGE == 1255 /* Hebrew (Windows) */
#define _DF1S	0
#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
				0xA0,0x21,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
				0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
				0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}

#elif _CODE_PAGE == 1256 /* Arabic (Windows) */
#define _DF1S	0
#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x8C,0x9D,0x9E,0x9F, \
				0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
				0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
				0x41,0xE1,0x41,0xE3,0xE4,0xE5,0xE6,0x43,0x45,0x45,0x45,0x45,0xEC,0xED,0x49,0x49,0xF0,0xF1,0xF2,0xF3,0x4F,0xF5,0xF6,0xF7,0xF8,0x55,0xFA,0x55,0x55,0xFD,0xFE,0xFF}

#elif _CODE_PAGE == 1257 /* Baltic (Windows) */
#define _DF1S	0
#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
				0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xA8,0xB9,0xAA,0xBB,0xBC,0xBD,0xBE,0xAF, \
				0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
				0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xF7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xFF}

#elif _CODE_PAGE == 1258 /* Vietnam (OEM, Windows) */
#define _DF1S	0
#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0xAC,0x9D,0x9E,0x9F, \
				0xA0,0x21,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
				0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
				0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xEC,0xCD,0xCE,0xCF,0xD0,0xD1,0xF2,0xD3,0xD4,0xD5,0xD6,0xF7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xFE,0x9F}

#elif _CODE_PAGE == 1	/* ASCII (for only non-LFN cfg) */
#if _USE_LFN
#error Cannot use LFN feature without valid code page.
#endif
#define _DF1S	0

#else
#error Unknown code page

#endif


/* Character code support macros */
#define IsUpper(c)	(((c)>='A')&&((c)<='Z'))
#define IsLower(c)	(((c)>='a')&&((c)<='z'))
#define IsDigit(c)	(((c)>='0')&&((c)<='9'))

#if _DF1S		/* Code page is DBCS */

#ifdef _DF2S	/* Two 1st byte areas */
#define IsDBCS1(c)	(((BYTE)(c) >= _DF1S && (BYTE)(c) <= _DF1E) || ((BYTE)(c) >= _DF2S && (BYTE)(c) <= _DF2E))
#else			/* One 1st byte area */
#define IsDBCS1(c)	((BYTE)(c) >= _DF1S && (BYTE)(c) <= _DF1E)
#endif

#ifdef _DS3S	/* Three 2nd byte areas */
#define IsDBCS2(c)	(((BYTE)(c) >= _DS1S && (BYTE)(c) <= _DS1E) || ((BYTE)(c) >= _DS2S && (BYTE)(c) <= _DS2E) || ((BYTE)(c) >= _DS3S && (BYTE)(c) <= _DS3E))
#else			/* Two 2nd byte areas */
#define IsDBCS2(c)	(((BYTE)(c) >= _DS1S && (BYTE)(c) <= _DS1E) || ((BYTE)(c) >= _DS2S && (BYTE)(c) <= _DS2E))
#endif

#else			/* Code page is SBCS */

#define IsDBCS1(c)	0
#define IsDBCS2(c)	0

#endif /* _DF1S */


/* Name status flags */
#define NS			11		/* Index of name status byte in fn[] */
#define NS_LOSS		0x01	/* Out of 8.3 format */
#define NS_LFN		0x02	/* Force to create LFN entry */
#define NS_LAST		0x04	/* Last segment */
#define NS_BODY		0x08	/* Lower case flag (body) */
#define NS_EXT		0x10	/* Lower case flag (ext) */
#define NS_DOT		0x20	/* Dot entry */


/* FAT sub-type boundaries */
/* Note that the FAT spec by Microsoft says 4085 but Windows works with 4087! */
#define MIN_FAT16	4086	/* Minimum number of clusters for FAT16 */
#define	MIN_FAT32	65526	/* Minimum number of clusters for FAT32 */


/* FatFs refers the members in the FAT structures as byte array instead of
/ structure member because the structure is not binary compatible between
/ different platforms */

#define BS_jmpBoot			0	/* Jump instruction (3) */
#define BS_OEMName			3	/* OEM name (8) */
#define BPB_BytsPerSec		11	/* Sector size [byte] (2) */
#define BPB_SecPerClus		13	/* Cluster size [sector] (1) */
#define BPB_RsvdSecCnt		14	/* Size of reserved area [sector] (2) */
#define BPB_NumFATs			16	/* Number of FAT copies (1) */
#define BPB_RootEntCnt		17	/* Number of root dir entries for FAT12/16 (2) */
#define BPB_TotSec16		19	/* Volume size [sector] (2) */
#define BPB_Media			21	/* Media descriptor (1) */
#define BPB_FATSz16			22	/* FAT size [sector] (2) */
#define BPB_SecPerTrk		24	/* Track size [sector] (2) */
#define BPB_NumHeads		26	/* Number of heads (2) */
#define BPB_HiddSec			28	/* Number of special hidden sectors (4) */
#define BPB_TotSec32		32	/* Volume size [sector] (4) */
#define BS_DrvNum			36	/* Physical drive number (2) */
#define BS_BootSig			38	/* Extended boot signature (1) */
#define BS_VolID			39	/* Volume serial number (4) */
#define BS_VolLab			43	/* Volume label (8) */
#define BS_FilSysType		54	/* File system type (1) */
#define BPB_FATSz32			36	/* FAT size [sector] (4) */
#define BPB_ExtFlags		40	/* Extended flags (2) */
#define BPB_FSVer			42	/* File system version (2) */
#define BPB_RootClus		44	/* Root dir first cluster (4) */
#define BPB_FSInfo			48	/* Offset of FSInfo sector (2) */
#define BPB_BkBootSec		50	/* Offset of backup boot sector (2) */
#define BS_DrvNum32			64	/* Physical drive number (2) */
#define BS_BootSig32		66	/* Extended boot signature (1) */
#define BS_VolID32			67	/* Volume serial number (4) */
#define BS_VolLab32			71	/* Volume label (8) */
#define BS_FilSysType32		82	/* File system type (1) */
#define	FSI_LeadSig			0	/* FSI: Leading signature (4) */
#define	FSI_StrucSig		484	/* FSI: Structure signature (4) */
#define	FSI_Free_Count		488	/* FSI: Number of free clusters (4) */
#define	FSI_Nxt_Free		492	/* FSI: Last allocated cluster (4) */
#define MBR_Table			446	/* MBR: Partition table offset (2) */
#define	SZ_PTE				16	/* MBR: Size of a partition table entry */
#define BS_55AA				510	/* Boot sector signature (2) */

#define	DIR_Name			0	/* Short file name (11) */
#define	DIR_Attr			11	/* Attribute (1) */
#define	DIR_NTres			12	/* NT flag (1) */
#define DIR_CrtTimeTenth	13	/* Created time sub-second (1) */
#define	DIR_CrtTime			14	/* Created time (2) */
#define	DIR_CrtDate			16	/* Created date (2) */
#define DIR_LstAccDate		18	/* Last accessed date (2) */
#define	DIR_FstClusHI		20	/* Higher 16-bit of first cluster (2) */
#define	DIR_WrtTime			22	/* Modified time (2) */
#define	DIR_WrtDate			24	/* Modified date (2) */
#define	DIR_FstClusLO		26	/* Lower 16-bit of first cluster (2) */
#define	DIR_FileSize		28	/* File size (4) */
#define	LDIR_Ord			0	/* LFN entry order and LLE flag (1) */
#define	LDIR_Attr			11	/* LFN attribute (1) */
#define	LDIR_Type			12	/* LFN type (1) */
#define	LDIR_Chksum			13	/* Sum of corresponding SFN entry */
#define	LDIR_FstClusLO		26	/* Filled by zero (0) */
#define	SZ_DIR				32		/* Size of a directory entry */
#define	LLE					0x40	/* Last long entry flag in LDIR_Ord */
#define	DDE					0xE5	/* Deleted directory entry mark in DIR_Name[0] */
#define	NDDE				0x05	/* Replacement of the character collides with DDE */


/*------------------------------------------------------------*/
/* Module private work area                                   */
/*------------------------------------------------------------*/
/* Note that uninitialized variables with static duration are
/  zeroed/nulled at start-up. If not, the compiler or start-up
/  routine is out of ANSI-C standard.
*/

#if _VOLUMES
static
FATFS *FatFs[_VOLUMES];	/* Pointer to the file system objects (logical drives) */
#else
#error Number of volumes must not be 0.
#endif

static
WORD Fsid;				/* File system mount ID */

#if _FS_RPATH
static
BYTE CurrVol;			/* Current drive */
#endif

#if _FS_LOCK
static
FILESEM	Files[_FS_LOCK];	/* File lock semaphores */
#endif

#if _USE_LFN == 0			/* No LFN feature */
#define	DEF_NAMEBUF			BYTE _sfn[12]
#define INIT_BUF(dobj)		(dobj).fn = _sfn
#define	FREE_BUF()

#elif _USE_LFN == 1			/* LFN feature with static working buffer */
static WCHAR _LfnBuf[_MAX_LFN + 1];
#define	DEF_NAMEBUF			BYTE _sfn[12]
#define INIT_BUF(dobj)		{ (dobj).fn = _sfn; (dobj).lfn = _LfnBuf; }
#define	FREE_BUF()

#elif _USE_LFN == 2 		/* LFN feature with dynamic working buffer on the stack */
#define	DEF_NAMEBUF			BYTE _sfn[12]; WCHAR _lbuf[_MAX_LFN+1]
#define INIT_BUF(dobj)		{ (dobj).fn = _sfn; (dobj).lfn = _lbuf; }
#define	FREE_BUF()

#elif _USE_LFN == 3 		/* LFN feature with dynamic working buffer on the heap */
#define	DEF_NAMEBUF			BYTE _sfn[12]; WCHAR *_lfn
#define INIT_BUF(dobj)		{ _lfn = ff_memalloc((_MAX_LFN + 1) * 2); \
							  if (!_lfn) LEAVE_FF((dobj).fs, FR_NOT_ENOUGH_CORE); \
							  (dobj).lfn = _lfn;	(dobj).fn = _sfn; }
#define	FREE_BUF()			ff_memfree(_lfn)

#else
#error Wrong LFN configuration.
#endif


#ifdef _EXCVT
static
const BYTE ExCvt[] = _EXCVT;	/* Upper conversion table for extended chars */
#endif






/*--------------------------------------------------------------------------

   Module Private Functions

---------------------------------------------------------------------------*/


/*-----------------------------------------------------------------------*/
/* String functions                                                      */
/*-----------------------------------------------------------------------*/

/* Copy memory to memory */
static void mem_cpy(void *_dst, const void *_src, UINT _cnt) {
	BYTE *_d = (BYTE *)_dst;
	const BYTE *_s = (const BYTE *)_src;

	#if _WORD_ACCESS == 1
		while (_cnt >= sizeof (int)) {
			*(int *)_d = *(int *)_s;
			_d += sizeof (int);
			_s += sizeof (int);
			_cnt -= sizeof (int);
		}
	#endif
	while (_cnt--)
		*_d++ = *_s++;
}

/* Fill memory */
static void mem_set (void *_dst, int _val, UINT _cnt) {
	BYTE *_d = (BYTE *)_dst;

	while (_cnt--)
		*_d++ = (BYTE)_val;
}

/* Compare memory to memory */
static int mem_cmp(const void *_dst, const void *_src, UINT _cnt) {
	const BYTE *_d = (const BYTE *)_dst, *_s = (const BYTE *)_src;
	int _r = 0;

	while (_cnt-- && (_r = *_d++ - *_s++) == 0) ;
	return _r;
}

/* Check if char is contained in the string */
static int chk_chr(const char *_str, int _chr) {
	while (*_str && *_str != _chr) _str++;
	return *_str;
}


#if _FS_REENTRANT

/** \brief Request/Release grant to access the volume.
 *
 * \param _fs	File system object.
 *
 */
static int lock_fs(FATFS *_fs)
{
	return ff_req_grant(_fs->sobj);
}

/** \brief Request/Release grant to access the volume.
 *
 * \param _fs	File system object.
 * \param _res	Result code to be returned.
 *
 */
static void unlock_fs(FATFS *_fs, FRESULT _res)
{
	if (_fs && _res != FR_NOT_ENABLED && _res != FR_INVALID_DRIVE && _res != FR_INVALID_OBJECT && _res != FR_TIMEOUT) {
		ff_rel_grant(_fs->sobj);
	}
}
#endif



/*-----------------------------------------------------------------------*/
/* File lock control functions                                           */
/*-----------------------------------------------------------------------*/
#if _FS_LOCK

/** \brief Check if the file can be accessed.
 *
 * \param _dj	Directory object pointing the file to be checked.
 * \param _acc	Desired access (0:Read, 1:Write, 2:Delete/Rename).
 *
 * \return Status
 *
 */
static FRESULT chk_lock(DIR* _dj, int _acc)
{
	UINT i, _be;

	/* Search file semaphore table */
	for (i = _be = 0; i < _FS_LOCK; i++) {
		if (Files[i].fs) {	/* Existing entry */
			if (Files[i].fs == _dj->fs &&	 	/* Check if the file matched with an open file */
				Files[i].clu == _dj->sclust &&
				Files[i].idx == _dj->index) break;
		} else {			/* Blank entry */
			_be++;
		}
	}
	if (i == _FS_LOCK)	/* The file is not opened */
		return (_be || _acc == 2) ? FR_OK : FR_TOO_MANY_OPEN_FILES;	/* Is there a blank entry for new file? */

	/* The file has been opened. Reject any open against writing file and all write mode open */
	return (_acc || Files[i].ctr == 0x100) ? FR_LOCKED : FR_OK;
}

/** \brief Check if an entry is available for a new file.
 *
 */
static int enq_lock(void)
{
	UINT i;

	for (i = 0; i < _FS_LOCK && Files[i].fs; i++) ;
	return (i == _FS_LOCK) ? 0 : 1;
}

/** \brief Increment file open counter and returns its index (0:int error).
 *
 * \param dj	Directory object pointing the file to register or increment.
 * \param acc	Desired access mode (0:Read, !0:Write).
 *
 */
static UINT inc_lock(DIR* _dj, int _acc)
{
	UINT i;


	for (i = 0; i < _FS_LOCK; i++) {	/* Find the file */
		if (Files[i].fs == _dj->fs &&
			Files[i].clu == _dj->sclust &&
			Files[i].idx == _dj->index) break;
	}

	if (i == _FS_LOCK) {				/* Not opened. Register it as new. */
		for (i = 0; i < _FS_LOCK && Files[i].fs; i++) ;
		if (i == _FS_LOCK) return 0;	/* No space to register (int err) */
		Files[i].fs = _dj->fs;
		Files[i].clu = _dj->sclust;
		Files[i].idx = _dj->index;
		Files[i].ctr = 0;
	}

	if (_acc && Files[i].ctr) return 0;	/* Access violation (int err) */

	Files[i].ctr = _acc ? 0x100 : Files[i].ctr + 1;	/* Set semaphore value */

	return i + 1;
}

/** \brief Decrement file open counter.
 *
 * \param i Semaphore index.
 *
 */
static FRESULT dec_lock(UINT i)
{
	WORD n;
	FRESULT _res;


	if (--i < _FS_LOCK) {
		n = Files[i].ctr;
		if (n == 0x100) n = 0;
		if (n) n--;
		Files[i].ctr = n;
		if (!n) Files[i].fs = 0;
		_res = FR_OK;
	}
	else {
		_res = FR_INT_ERR;
	}
	return _res;
}

/** \brief Clear lock entries of the volume.
 *
 * \param _fs	File system object.
 *
 */
static void clear_lock(FATFS *_fs)
{
	UINT i;

	for (i = 0; i < _FS_LOCK; i++) {
		if (Files[i].fs == _fs) Files[i].fs = 0;
	}
}
#endif


#if !_FS_READONLY

/** \brief Move/Flush disk access window .
 *
 * \param _fs	File system object.
 *
 * \return Status.
 *
 */
static FRESULT sync_window(FATFS *_fs)
{
	DWORD _wsect;
	UINT _nf;
	DRESULT _res_io;
	
	if (_fs->wflag) {	/* Write back the sector if it is dirty */
		_wsect = _fs->winsect;	/* Current sector number */
		_res_io = disk_write(_fs->drv, _fs->win, _wsect, 1);
		if (_res_io != RES_OK) {
			return FR_DISK_ERR;
		}
		_fs->wflag = 0;
		if (_wsect >= _fs->fatbase && _wsect < (_fs->fatbase + _fs->fsize)) {	/* In FAT area? */
			for (_nf = _fs->n_fats; _nf >= 2; _nf--) {	/* Reflect the change to all FAT copies */
				_wsect += _fs->fsize;
				_res_io = disk_write(_fs->drv, _fs->win, _wsect, 1);
				if (_res_io != RES_OK) {
					return FR_DISK_ERR;
				}
			}
		}
	}
	return FR_OK;
}
#endif

/** \brief Move window.
 *
 * \param _fs		File system object.
 * \param _sector	Sector number to make appearance in the fs->win[].
 *
 * \return	Status.
 *
 */
static FRESULT move_window(FATFS *_fs, DWORD _sector)
{
	DRESULT _io_status;
	
	if(_sector != _fs->winsect) {	/* Changed current window */
		#if !_FS_READONLY
			if (sync_window(_fs) != FR_OK) {
				return FR_DISK_ERR;
			}
		#endif
		
		_io_status = disk_read(_fs->drv, _fs->win, _sector, 1);
		if (_io_status != RES_OK) {
			return FR_DISK_ERR;
		}
		
		_fs->winsect = _sector;
	}

	return FR_OK;
}


#if !_FS_READONLY

/** \brief Synchronize file system and storage device.
 *
 * \param _fs	File system object.
 *
 * \return Status. FR_OK: successful, FR_DISK_ERR: failed.
 *
 */
static FRESULT sync_fs(FATFS *_fs)
{
	FRESULT _res;
	DRESULT _io_status;
	
	_res = sync_window(_fs);
	if (_res == FR_OK) {
		/* Update FSInfo sector if needed */
		if (_fs->fs_type == FS_FAT32 && _fs->fsi_flag) {
			_fs->winsect = 0;
			/* Create FSInfo structure */
			mem_set(_fs->win, 0, 512);
			ST_WORD(_fs->win + BS_55AA, 0xAA55);
			ST_DWORD(_fs->win + FSI_LeadSig, 0x41615252);
			ST_DWORD(_fs->win + FSI_StrucSig, 0x61417272);
			ST_DWORD(_fs->win + FSI_Free_Count, _fs->free_clust);
			ST_DWORD(_fs->win + FSI_Nxt_Free, _fs->last_clust);
			/* Write it into the FSInfo sector */
			disk_write(_fs->drv, _fs->win, _fs->fsi_sector, 1);
			_fs->fsi_flag = 0;
		}
		/* Make sure that no pending write process in the physical drive */
		_io_status = disk_ioctl(_fs->drv, CTRL_SYNC, 0);
		if (_io_status != RES_OK) {
			_res = FR_DISK_ERR;
		}
	}
	
	return _res;
}
#endif


/** \brief Get sector# from cluster# .
 *
 * \param _fs	File system object.
 * \param _clst	Cluster# to be converted.
 *
 * \return Status	!=0: Sector number, 0: Failed - invalid cluster#.
 *
 */
static DWORD clust2sect(FATFS *_fs, DWORD _clst)
{
	_clst -= 2;
	if (_clst >= (_fs->n_fatent - 2)) return 0;		/* Invalid cluster# */
	return _clst * _fs->csize + _fs->database;
}

/** \brief FAT access - Read value of a FAT entry.
 *
 * \param fs	File system object.
 * \param clst	Cluster# to get the link information.
 *
 * \return	Status	0xFFFFFFFF:Disk error, 1:Internal error, Else:Cluster status.
 *
 */
static DWORD get_fat(FATFS *_fs, DWORD _clst)
{
	UINT _wc, _bc;
	BYTE *_p;


	if (_clst < 2 || _clst >= _fs->n_fatent) {	/* Check range */
		return 1;
	}

	switch (_fs->fs_type) {
		case FS_FAT12 :
			_bc = (UINT)_clst; _bc += _bc / 2;
			if (move_window(_fs, _fs->fatbase + (_bc / SS(_fs)))) break;
			_wc = _fs->win[_bc % SS(_fs)]; _bc++;
			if (move_window(_fs, _fs->fatbase + (_bc / SS(_fs)))) break;
			_wc |= _fs->win[_bc % SS(_fs)] << 8;
			return (_clst & 1) ? (_wc >> 4) : (_wc & 0xFFF);
			
		case FS_FAT16 :
			if (move_window(_fs, _fs->fatbase + (_clst / (SS(_fs) / 2)))) break;
			_p = &_fs->win[_clst * 2 % SS(_fs)];
			return LD_WORD(_p);

		case FS_FAT32 :
			if (move_window(_fs, _fs->fatbase + (_clst / (SS(_fs) / 4)))) break;
			_p = &_fs->win[_clst * 4 % SS(_fs)];
			return LD_DWORD(_p) & 0x0FFFFFFF;
		}

	return 0xFFFFFFFF;	/* An error occurred at the disk I/O layer */
}

#if !_FS_READONLY

/** \brief FAT access - Change value of a FAT entry.
 *
 * \param _fs		File system object.
 * \param _clst		Cluster# to be changed in range of 2 to fs->n_fatent - 1.
 * \param _val		New value to mark the cluster.
 *
 */
static FRESULT put_fat(FATFS *_fs, DWORD _clst, DWORD _val)
{
	UINT _bc;
	BYTE *_p;
	FRESULT _res;


	if (_clst < 2 || _clst >= _fs->n_fatent) {	/* Check range */
		_res = FR_INT_ERR;
	}
	else {
		switch (_fs->fs_type) {
			case FS_FAT12 :
				_bc = (UINT)_clst; _bc += _bc / 2;
				_res = move_window(_fs, _fs->fatbase + (_bc / SS(_fs)));
				if (_res != FR_OK) break;
				_p = &_fs->win[_bc % SS(_fs)];
				*_p = (_clst & 1) ? ((*_p & 0x0F) | ((BYTE)_val << 4)) : (BYTE)_val;
				_bc++;
				_fs->wflag = 1;
				_res = move_window(_fs, _fs->fatbase + (_bc / SS(_fs)));
				if (_res != FR_OK) break;
				_p = &_fs->win[_bc % SS(_fs)];
				*_p = (_clst & 1) ? (BYTE)(_val >> 4) : ((*_p & 0xF0) | ((BYTE)(_val >> 8) & 0x0F));
			break;

			case FS_FAT16 :
				_res = move_window(_fs, _fs->fatbase + (_clst / (SS(_fs) / 2)));
				if (_res != FR_OK) break;
				_p = &_fs->win[_clst * 2 % SS(_fs)];
				ST_WORD(_p, (WORD)_val);
			break;

			case FS_FAT32 :
				_res = move_window(_fs, _fs->fatbase + (_clst / (SS(_fs) / 4)));
				if (_res != FR_OK) break;
				_p = &_fs->win[_clst * 4 % SS(_fs)];
				_val |= LD_DWORD(_p) & 0xF0000000;
				ST_DWORD(_p, _val);
			break;

		default :
			_res = FR_INT_ERR;
		}
		_fs->wflag = 1;
	}

	return _res;
}
#endif /* !_FS_READONLY */


#if !_FS_READONLY

/** \brief FAT handling - Remove a cluster chain.
 *
 * \param fs	File system object.
 * \param clst	Cluster# to remove a chain from.
 *
 * \return Status.
 *
 */
static FRESULT remove_chain(FATFS *_fs, DWORD _clst)
{
	FRESULT _res;
	DWORD _nxt;
	#if _USE_ERASE
		DWORD _scl = _clst, _ecl = _clst, _rt[2];
	#endif

	if (_clst < 2 || _clst >= _fs->n_fatent) { /* Check range */
		_res = FR_INT_ERR;
	}
	else {
		_res = FR_OK;
		while (_clst < _fs->n_fatent) {			/* Not a last link? */
			_nxt = get_fat(_fs, _clst);			/* Get cluster status */
			if (_nxt == 0) break;				/* Empty cluster? */
			if (_nxt == 1) { _res = FR_INT_ERR; break; }	/* Internal error? */
			if (_nxt == 0xFFFFFFFF) { _res = FR_DISK_ERR; break; }	/* Disk error? */
			_res = put_fat(_fs, _clst, 0);			/* Mark the cluster "empty" */
			if (_res != FR_OK) break;
			if (_fs->free_clust != 0xFFFFFFFF) {	/* Update FSInfo */
				_fs->free_clust++;
				_fs->fsi_flag = 1;
			}
			#if _USE_ERASE
				if (_ecl + 1 == _nxt) {	/* Is next cluster contiguous? */
					_ecl = _nxt;
				}
				else {				/* End of contiguous clusters */ 
					_rt[0] = clust2sect(_fs, _scl);					/* Start sector */
					_rt[1] = clust2sect(_fs, _ecl) + _fs->csize - 1;	/* End sector */
					disk_ioctl(_fs->drv, CTRL_ERASE_SECTOR, _rt);		/* Erase the block */
					_scl = _ecl = _nxt;
				}
			#endif
			_clst = _nxt;	/* Next cluster */
		}
	}

	return _res;
}
#endif


#if !_FS_READONLY

/** \brief FAT handling - Stretch or Create a cluster chain.
 *
 * \param _fs	File system object.
 * \param _clst	Cluster# to stretch. 0 means create a new chain.
 *
 * \return Cluster. 0:No free cluster, 1:Internal error, 0xFFFFFFFF:Disk error, >=2:New cluster#
 *
 */
static DWORD create_chain(FATFS *_fs, DWORD _clst)
{
	DWORD _cs, _ncl, _scl;
	FRESULT _res;


	if (_clst == 0) {		/* Create a new chain */
		_scl = _fs->last_clust;			/* Get suggested start point */
		if (!_scl || _scl >= _fs->n_fatent) _scl = 1;
	}
	else {					/* Stretch the current chain */
		_cs = get_fat(_fs, _clst);				/* Check the cluster status */
		if (_cs < 2) {
			return 1;							/* It is an invalid cluster */
		}
		if (_cs < _fs->n_fatent) return _cs;	/* It is already followed by next cluster */
		_scl = _clst;
	}

	_ncl = _scl;	/* Start cluster */
	for (;;) {
		_ncl++;								/* Next cluster */
		if (_ncl >= _fs->n_fatent) {		/* Wrap around */
			_ncl = 2;
			if (_ncl > _scl) return 0;		/* No free cluster */
		}
		_cs = get_fat(_fs, _ncl);			/* Get the cluster status */
		if (_cs == 0) break;				/* Found a free cluster */
		if (_cs == 0xFFFFFFFF || _cs == 1)	/* An error occurred */
			return _cs;
		if (_ncl == _scl) return 0;			/* No free cluster */
	}
	
	_res = put_fat(_fs, _ncl, 0x0FFFFFFF);	/* Mark the new cluster "last link" */
	if (_res == FR_OK && _clst != 0) {
		_res = put_fat(_fs, _clst, _ncl);	/* Link it to the previous one if needed */
	}
	if (_res == FR_OK) {
		_fs->last_clust = _ncl;				/* Update FSINFO */
		if (_fs->free_clust != 0xFFFFFFFF) {
			_fs->free_clust--;
			_fs->fsi_flag = 1;
		}
	}
	else {
		_ncl = (_res == FR_DISK_ERR) ? 0xFFFFFFFF : 1;
	}

	return _ncl;		/* Return new cluster number or error code */
}
#endif /* !_FS_READONLY */


#if _USE_FASTSEEK

/** \brief FAT handling - Convert offset into cluster with link map table.
 *
 * \param _fp	Pointer to the file object.
 * \param _ofs	File offset to be converted to cluster#.
 *
 * \return <2:Error, >=2:Cluster number.
 *
 */
static DWORD clmt_clust(FIL *_fp, DWORD _ofs)
{
	DWORD _cl, _ncl, *_tbl;


	_tbl = _fp->cltbl + 1;		/* Top of CLMT */
	_cl = _ofs / SS(_fp->fs) / _fp->fs->csize;	/* Cluster order from top of the file */
	for (;;) {
		_ncl = *_tbl++;				/* Number of cluters in the fragment */
		if (!_ncl) return 0;		/* End of table? (error) */
		if (_cl < _ncl) break;		/* In this fragment? */
		_cl -= _ncl; _tbl++;		/* Next fragment */
	}
	return _cl + *_tbl;	/* Return the cluster number */
}
#endif	/* _USE_FASTSEEK */


/** \brief Directory handling - Set directory index.
 *
 * \param _dj	Pointer to directory object.
 * \param _idx	Index of directory table.
 *
 * \return Status
 */
static FRESULT dir_sdi(DIR *_dj, WORD _idx)
{
	DWORD _clst;
	WORD _ic;


	_dj->index = _idx;
	_clst = _dj->sclust;
	if (_clst == 1 || _clst >= _dj->fs->n_fatent) {	/* Check start cluster range */
		return FR_INT_ERR;
	}
	if (!_clst && _dj->fs->fs_type == FS_FAT32) {		/* Replace cluster# 0 with root cluster# if in FAT32 */
		_clst = _dj->fs->dirbase;
	}

	if (_clst == 0) {	/* Static table (root-dir in FAT12/16) */
		_dj->clust = _clst;
		if (_idx >= _dj->fs->n_rootdir) {		/* Index is out of range */
			return FR_INT_ERR;
		}
		_dj->sect = _dj->fs->dirbase + _idx / (SS(_dj->fs) / SZ_DIR);	/* Sector# */
	}
	else {				/* Dynamic table (sub-dirs or root-dir in FAT32) */
		_ic = SS(_dj->fs) / SZ_DIR * _dj->fs->csize;		/* Entries per cluster */
		while (_idx >= _ic) {	/* Follow cluster chain */
			_clst = get_fat(_dj->fs, _clst);				/* Get next cluster */
			if (_clst == 0xFFFFFFFF) return FR_DISK_ERR;	/* Disk error */
			if (_clst < 2 || _clst >= _dj->fs->n_fatent) {	/* Reached to end of table or int error */
				return FR_INT_ERR;
			}
			_idx -= _ic;
		}
		_dj->clust = _clst;
		_dj->sect = clust2sect(_dj->fs, _clst) + _idx / (SS(_dj->fs) / SZ_DIR);	/* Sector# */
	}

	_dj->dir = _dj->fs->win + (_idx % (SS(_dj->fs) / SZ_DIR)) * SZ_DIR;	/* Ptr to the entry in the sector */

	return FR_OK;	/* Seek succeeded */
}


/** \brief Directory handling - Move directory table index next.
 *
 * \param _dj		Pointer to the directory object.
 * \param _stretch	0: Do not stretch table, 1: Stretch table if needed.
 *
 * \return Status. FR_OK:Succeeded, FR_NO_FILE:End of table, FR_DENIED:Could not stretch.
 *
 */
static FRESULT dir_next(DIR *_dj, int _stretch)
{
	DWORD _clst;
	WORD i;


#if _FS_READONLY
	/* To suppress warning on read-only cfg. */
	_stretch = 0;
#endif

	i = _dj->index + 1;
	if (!i || !_dj->sect) {		/* Report EOT when index has reached 65535 */
		return FR_NO_FILE;
	}

	if (!(i % (SS(_dj->fs) / SZ_DIR))) {	/* Sector changed? */
		_dj->sect++;					/* Next sector */

		if (_dj->clust == 0) {		/* Static table */
			if (i >= _dj->fs->n_rootdir)	/* Report EOT when end of table */
				return FR_NO_FILE;
		}
		else {					/* Dynamic table */
			if (((i / (SS(_dj->fs) / SZ_DIR)) & (_dj->fs->csize - 1)) == 0) {	/* Cluster changed? */
				_clst = get_fat(_dj->fs, _dj->clust);				/* Get next cluster */
				if (_clst <= 1) {
					return FR_INT_ERR;
				}
				if (_clst == 0xFFFFFFFF) {
					return FR_DISK_ERR;
				}
				if (_clst >= _dj->fs->n_fatent) {					/* When it reached end of dynamic table */
					#if !_FS_READONLY
						BYTE _c;
						if (!_stretch) {
							return FR_NO_FILE;						/* When do not stretch, report EOT */
						}
						_clst = create_chain(_dj->fs, _dj->clust);	/* Stretch cluster chain */
						if (_clst == 0) {
							return FR_DENIED;			/* No free cluster */
						}
						if (_clst == 1) {
							return FR_INT_ERR;
						}
						if (_clst == 0xFFFFFFFF) {
							return FR_DISK_ERR;
						}
						/* Clean-up stretched table */
						if (sync_window(_dj->fs)) {
							return FR_DISK_ERR;	/* Flush active window */
						}
						mem_set(_dj->fs->win, 0, SS(_dj->fs));			/* Clear window buffer */
						_dj->fs->winsect = clust2sect(_dj->fs, _clst);	/* Cluster start sector */
						for (_c = 0; _c < _dj->fs->csize; _c++) {		/* Fill the new cluster with 0 */
							_dj->fs->wflag = 1;
							if (sync_window(_dj->fs)) {
								return FR_DISK_ERR;
							}
							_dj->fs->winsect++;
						}
						_dj->fs->winsect -= _c;						/* Rewind window address */
					#else
						return FR_NO_FILE;	/* Report EOT */
					#endif
				}
				_dj->clust = _clst;				/* Initialize data for new cluster */
				_dj->sect = clust2sect(_dj->fs, _clst);
			}
		}
	}

	_dj->index = i;
	_dj->dir = _dj->fs->win + (i % (SS(_dj->fs) / SZ_DIR)) * SZ_DIR;

	return FR_OK;
}


#if !_FS_READONLY

/** \brief Directory handling - Reserve directory entry.
 *
 * \param _dj	Pointer to the directory object.
 * \param _nent	Number of contiguous entries to allocate (1-21).
 *
 */
static FRESULT dir_alloc(DIR *_dj, UINT _nent)
{
	FRESULT _res;
	UINT n;


	_res = dir_sdi(_dj, 0);
	if (_res == FR_OK) {
		n = 0;
		do {
			_res = move_window(_dj->fs, _dj->sect);
			if (_res != FR_OK) break;
			if (_dj->dir[0] == DDE || _dj->dir[0] == 0) {	/* Is it a blank entry? */
				if (++n == _nent) break;	/* A block of contiguous entry is found */
			} else {
				n = 0;					/* Not a blank entry. Restart to search */
			}
			_res = dir_next(_dj, 1);		/* Next entry with table stretch enabled */
		} while (_res == FR_OK);
	}
	return _res;
}
#endif


/** \brief Directory handling - Load/Store start cluster number.
 *
 * \param fs	Pointer to the fs object.
 * \param dir	Pointer to the directory entry
 *
 * \return Cluster Number.
 *
 */
static DWORD ld_clust(FATFS *_fs, BYTE *_dir)
{
	DWORD _cl;

	_cl = LD_WORD(_dir + DIR_FstClusLO);
	if (_fs->fs_type == FS_FAT32)
		_cl |= (DWORD)LD_WORD(_dir + DIR_FstClusHI) << 16;

	return _cl;
}


#if !_FS_READONLY

/** \brief Set cluster with value.
 *
 * \param dir	Pointer to the directory entry.
 * \param cl	Value to be set
 *
 */
static void st_clust (BYTE *_dir, DWORD _cl)
{
	ST_WORD(_dir + DIR_FstClusLO, _cl);
	ST_WORD(_dir + DIR_FstClusHI, _cl >> 16);
}
#endif



/*-----------------------------------------------------------------------*/
/* LFN handling - Test/Pick/Fit an LFN segment from/to directory entry   */
/*-----------------------------------------------------------------------*/
#if _USE_LFN
static const BYTE LfnOfs[] = {1,3,5,7,9,14,16,18,20,22,24,28,30};	/* Offset of LFN chars in the directory entry */


/** \brief Compare Long File Name.
 *
 * \param _lfnbuf	Pointer to the LFN to be compared.
 * \param _dir		Pointer to the directory entry containing a part of LFN.
 *
 * \return Result 1:Matched, 0:Not matched.
 *
 */
static int cmp_lfn(WCHAR *_lfnbuf, BYTE *_dir)
{
	UINT i, s;
	WCHAR _wc, _uc;


	i = ((_dir[LDIR_Ord] & ~LLE) - 1) * 13;	/* Get offset in the LFN buffer */
	s = 0; _wc = 1;
	do {
		_uc = LD_WORD(_dir + LfnOfs[s]);	/* Pick an LFN character from the entry */
		if (_wc) {	/* Last char has not been processed */
			_wc = ff_wtoupper(_uc);		/* Convert it to upper case */
			if (i >= _MAX_LFN || _wc != ff_wtoupper(_lfnbuf[i++]))	/* Compare it */
				return 0;				/* Not matched */
		} else {
			if (_uc != 0xFFFF) return 0;	/* Check filler */
		}
	} while (++s < 13);				/* Repeat until all chars in the entry are checked */

	if ((_dir[LDIR_Ord] & LLE) && _wc && _lfnbuf[i])	/* Last segment matched but different length */
		return 0;

	return 1;						/* The part of LFN matched */
}


/** \brief Pick LFN.
 *
 * \param _lfnbuf	Pointer to the Unicode-LFN buffer.
 * \param _dir		Pointer to the directory entry.
 *
 * \return Result 1:Succeeded, 0:Buffer overflow.
 *
 */
static int pick_lfn(WCHAR *_lfnbuf, BYTE *_dir)
{
	UINT i, s;
	WCHAR _wc, _uc;


	i = ((_dir[LDIR_Ord] & 0x3F) - 1) * 13;	/* Offset in the LFN buffer */

	s = 0; _wc = 1;
	do {
		_uc = LD_WORD(_dir + LfnOfs[s]);		/* Pick an LFN character from the entry */
		if (_wc) {	/* Last char has not been processed */
			if (i >= _MAX_LFN) return 0;	/* Buffer overflow? */
			_lfnbuf[i++] = _wc = _uc;			/* Store it */
		}
		else {
			if (_uc != 0xFFFF) return 0;		/* Check filler */
		}
	} while (++s < 13);						/* Read all character in the entry */

	if (_dir[LDIR_Ord] & LLE) {				/* Put terminator if it is the last LFN part */
		if (i >= _MAX_LFN) return 0;		/* Buffer overflow? */
		_lfnbuf[i] = 0;
	}

	return 1;
}


#if !_FS_READONLY

/** \brief Fit LFN.
 *
 * \param _lfnbuf	Pointer to the LFN buffer.
 * \param _dir		Pointer to the directory entry.
 * \param _ord		LFN order (1-20).
 * \param _sum		SFN sum.
 *
 */
static void fit_lfn(const WCHAR *_lfnbuf, BYTE *_dir, BYTE _ord, BYTE _sum)
{
	UINT i, s;
	WCHAR _wc;


	_dir[LDIR_Chksum] = _sum;			/* Set check sum */
	_dir[LDIR_Attr] = AM_LFN;		/* Set attribute. LFN entry */
	_dir[LDIR_Type] = 0;
	ST_WORD(_dir + LDIR_FstClusLO, 0);

	i = (_ord - 1) * 13;				/* Get offset in the LFN buffer */
	s = _wc = 0;
	do {
		if (_wc != 0xFFFF) _wc = _lfnbuf[i++];	/* Get an effective char */
		ST_WORD(_dir + LfnOfs[s], _wc);	/* Put it */
		if (!_wc) _wc = 0xFFFF;		/* Padding chars following last char */
	} while (++s < 13);
	if (_wc == 0xFFFF || !_lfnbuf[i]) _ord |= LLE;	/* Bottom LFN part is the start of LFN sequence */
	_dir[LDIR_Ord] = _ord;			/* Set the LFN order */
}

#endif
#endif


#if _USE_LFN

/** \brief Create numbered name.
 *
 * \param _dst	Pointer to generated SFN.
 * \param _src	Pointer to source SFN to be modified.
 * \param _lfn	Pointer to LFN.
 * \param _seq	Sequence number.
 *
 */
static void gen_numname(BYTE *_dst, const BYTE *_src, const WCHAR *_lfn, WORD _seq)
{
	BYTE _ns[8], _c;
	UINT i, j;


	mem_cpy(_dst, _src, 11);

	if (_seq > 5) {	/* On many collisions, generate a hash number instead of sequential number */
		do _seq = (_seq >> 1) + (_seq << 15) + (WORD)*_lfn++; while (*_lfn);
	}

	/* itoa (hexadecimal) */
	i = 7;
	do {
		_c = (_seq % 16) + '0';
		if (_c > '9') _c += 7;
		_ns[i--] = _c;
		_seq /= 16;
	} while (_seq);
	_ns[i] = '~';

	/* Append the number */
	for (j = 0; j < i && _dst[j] != ' '; j++) {
		if (IsDBCS1(_dst[j])) {
			if (j == i - 1) break;
			j++;
		}
	}
	do {
		_dst[j++] = (i < 8) ? _ns[i++] : ' ';
	} while (j < 8);
}
#endif


#if _USE_LFN

/** \brief Calculate sum of an SFN.
 *
 * \param _dir	Ptr to directory entry.
 *
 */
static BYTE sum_sfn(const BYTE *_dir)
{
	BYTE _sum = 0;
	UINT n = 11;

	do _sum = (_sum >> 1) + (_sum << 7) + *_dir++; while (--n);
	return _sum;
}
#endif


/** \brief Directory handling - Find an object in the directory.
 *
 * \param _dj	Pointer to the directory object linked to the file name.
 *
 */
static FRESULT dir_find(DIR *_dj)
{
	FRESULT _res;
	BYTE _c, *_dir;
	#if _USE_LFN
		BYTE _a, _ord, _sum;
	#endif
	
	_res = dir_sdi(_dj, 0);			/* Rewind directory object */
	if (_res != FR_OK) return _res;
	
	#if _USE_LFN
		_ord = _sum = 0xFF;
	#endif
	do {
		_res = move_window(_dj->fs, _dj->sect);
		if (_res != FR_OK) {
			break;
		}
		_dir = _dj->dir;					/* Ptr to the directory entry of current index */
		_c = _dir[DIR_Name];
		if (_c == 0) {						/* Reached to end of table */
			_res = FR_NO_FILE;
			break;
		}	
		#if _USE_LFN	/* LFN configuration */
			_a = _dir[DIR_Attr] & AM_MASK;
			if (_c == DDE || ((_a & AM_VOL) && _a != AM_LFN)) {	/* An entry without valid data */
				_ord = 0xFF;
			}
			else {
				if (_a == AM_LFN) {			/* An LFN entry is found */
					if (_dj->lfn) {
						if (_c & LLE) {		/* Is it start of LFN sequence? */
							_sum = _dir[LDIR_Chksum];
							_c &= ~LLE; _ord = _c;	/* LFN start order */
							_dj->lfn_idx = _dj->index;
						}
						/* Check validity of the LFN entry and compare it with given name */
						_ord = (_c == _ord && _sum == _dir[LDIR_Chksum] && cmp_lfn(_dj->lfn, _dir)) ? _ord - 1 : 0xFF;
					}
				}
				else {					/* An SFN entry is found */
					if (!_ord && _sum == sum_sfn(_dir)) break;	/* LFN matched? */
					_ord = 0xFF; _dj->lfn_idx = 0xFFFF;	/* Reset LFN sequence */
					if (!(_dj->fn[NS] & NS_LOSS) && !mem_cmp(_dir, _dj->fn, 11)) break;	/* SFN matched? */
				}
			}
		/* Non LFN configuration */
		#else /* _USE_LFN */	
			if (!(_dir[DIR_Attr] & AM_VOL) && !mem_cmp(_dir, _dj->fn, 11)) /* Is it a valid entry? */
				break;
		#endif /* _USE_LFN */
		_res = dir_next(_dj, 0);		/* Next entry */
	} while (_res == FR_OK);

	return _res;
}

#if _FS_MINIMIZE <= 1 || _USE_LABEL || _FS_RPATH >= 2

/** \brief Read an object from the directory.
 *
 * \param _dj	Pointer to the directory object.
 * \param _vol	Filtered by 0:file/dir or 1:volume label.
 *
 */
static FRESULT dir_read(DIR *_dj, int _vol)
{
	FRESULT _res;
	BYTE _a, _c, *_dir;
	#if _USE_LFN
		BYTE _ord = 0xFF, _sum = 0xFF;
	#endif

	_res = FR_NO_FILE;
	while (_dj->sect) {
		_res = move_window(_dj->fs, _dj->sect);
		if (_res != FR_OK) break;
		_dir = _dj->dir;					/* Ptr to the directory entry of current index */
		_c = _dir[DIR_Name];
		if (_c == 0) { _res = FR_NO_FILE; break; }	/* Reached to end of table */
		_a = _dir[DIR_Attr] & AM_MASK;
		#if _USE_LFN	/* LFN configuration */
			if (_c == DDE || (!_FS_RPATH && _c == '.') || (_a == AM_VOL) != _vol) {	/* An entry without valid data */
				_ord = 0xFF;
			}
			else {
				if (_a == AM_LFN) {			/* An LFN entry is found */
					if (_c & LLE) {			/* Is it start of LFN sequence? */
						_sum = _dir[LDIR_Chksum];
						_c &= ~LLE; _ord = _c;
						_dj->lfn_idx = _dj->index;
					}
					/* Check LFN validity and capture it */
					_ord = (_c == _ord && _sum == _dir[LDIR_Chksum] && pick_lfn(_dj->lfn, _dir)) ? _ord - 1 : 0xFF;
				}
				else {					/* An SFN entry is found */
					if (_ord || _sum != sum_sfn(_dir))	/* Is there a valid LFN? */
						_dj->lfn_idx = 0xFFFF;		/* It has no LFN. */
					break;
				}
			}
		#else		/* Non LFN configuration */
			if (_c != DDE && (_FS_RPATH || _c != '.') && _a != AM_LFN && (_a == AM_VOL) == _vol)	/* Is it a valid entry? */
				break;
		#endif
		_res = dir_next(_dj, 0);				/* Next entry */
		if (_res != FR_OK) break;
	}

	if (_res != FR_OK) _dj->sect = 0;

	return _res;
}
#endif	/* _FS_MINIMIZE <= 1 || _USE_LABEL || _FS_RPATH >= 2 */


#if !_FS_READONLY

/** \brief Register an object to the directory.
 *
 * \param _dj	Target directory with object name to be created.
 *
 * \return FR_OK:Successful, FR_DENIED:No free entry or too many SFN collision, FR_DISK_ERR:Disk error.
 *
 */
static FRESULT dir_register(DIR *_dj)
{
	FRESULT _res;
	#if _USE_LFN	/* LFN configuration */
		WORD _n, _ne;
		BYTE _sn[12], *_fn, _sum;
		WCHAR *_lfn;
		
		_fn = _dj->fn; _lfn = _dj->lfn;
		mem_cpy(_sn, _fn, 12);
		
		if (_FS_RPATH && (_sn[NS] & NS_DOT))		/* Cannot create dot entry */
			return FR_INVALID_NAME;
			
		if (_sn[NS] & NS_LOSS) {			/* When LFN is out of 8.3 format, generate a numbered name */
			_fn[NS] = 0; _dj->lfn = 0;			/* Find only SFN */
			for (_n = 1; _n < 100; _n++) {
				gen_numname(_fn, _sn, _lfn, _n);	/* Generate a numbered name */
				_res = dir_find(_dj);				/* Check if the name collides with existing SFN */
				if (_res != FR_OK) break;
			}
			if (_n == 100) return FR_DENIED;		/* Abort if too many collisions */
			if (_res != FR_NO_FILE) return _res;	/* Abort if the result is other than 'not collided' */
			_fn[NS] = _sn[NS];
			_dj->lfn = _lfn;
		}

		if (_sn[NS] & NS_LFN) {			/* When LFN is to be created, allocate entries for an SFN + LFNs. */
			for (_n = 0; _lfn[_n]; _n++) ;
			_ne = (_n + 25) / 13;
		}
		else {						/* Otherwise allocate an entry for an SFN  */
			_ne = 1;
		}
		_res = dir_alloc(_dj, _ne);		/* Allocate entries */
		
		if (_res == FR_OK && --_ne) {		/* Set LFN entry if needed */
			_res = dir_sdi(_dj, (WORD)(_dj->index - _ne));
			if (_res == FR_OK) {
				_sum = sum_sfn(_dj->fn);	/* Sum value of the SFN tied to the LFN */
				do {					/* Store LFN entries in bottom first */
					_res = move_window(_dj->fs, _dj->sect);
					if (_res != FR_OK) break;
					fit_lfn(_dj->lfn, _dj->dir, (BYTE)_ne, _sum);
					_dj->fs->wflag = 1;
					_res = dir_next(_dj, 0);	/* Next entry */
				} while (_res == FR_OK && --_ne);
			}
		}
	#else	/* Non LFN configuration */
		_res = dir_alloc(_dj, 1);		/* Allocate an entry for SFN */
	#endif

	if (_res == FR_OK) {				/* Set SFN entry */
		_res = move_window(_dj->fs, _dj->sect);
		if (_res == FR_OK) {
			mem_set(_dj->dir, 0, SZ_DIR);	/* Clean the entry */
			mem_cpy(_dj->dir, _dj->fn, 11);	/* Put SFN */
			#if _USE_LFN
				_dj->dir[DIR_NTres] = *(_dj->fn+NS) & (NS_BODY | NS_EXT);	/* Put NT flag */
			#endif
			_dj->fs->wflag = 1;
		}
	}

	return _res;
}
#endif /* !_FS_READONLY */

#if !_FS_READONLY && !_FS_MINIMIZE

/** \brief Remove an object from the directory.
 *
 * \param _dj	Directory object pointing the entry to be removed.
 * 
 * \return FR_OK: Successful, FR_DISK_ERR: A disk error.
 *
 */
static FRESULT dir_remove(DIR *_dj)
{
	FRESULT _res;
	#if _USE_LFN	/* LFN configuration */
		WORD i;
		
		i = _dj->index;	/* SFN index */
		_res = dir_sdi(_dj, (WORD)((_dj->lfn_idx == 0xFFFF) ? i : _dj->lfn_idx));	/* Goto the SFN or top of the LFN entries */
		if (_res == FR_OK) {
			do {
				_res = move_window(_dj->fs, _dj->sect);
				if (_res != FR_OK) break;
				*_dj->dir = DDE;			/* Mark the entry "deleted" */
				_dj->fs->wflag = 1;
				if (_dj->index >= i) break;	/* When reached SFN, all entries of the object has been deleted. */
				_res = dir_next(_dj, 0);		/* Next entry */
			} while (_res == FR_OK);
			if (_res == FR_NO_FILE) _res = FR_INT_ERR;
		}
	#else			/* Non LFN configuration */
		_res = dir_sdi(_dj, _dj->index);
		if (_res == FR_OK) {
			_res = move_window(_dj->fs, _dj->sect);
			if (_res == FR_OK) {
				*_dj->dir = DDE;			/* Mark the entry "deleted" */
				_dj->fs->wflag = 1;
			}
		}
	#endif
	
	return _res;
}
#endif /* !_FS_READONLY */


/* \brief Pick a segment and create the object name in directory form.
 *
 * \param _dj	Pointer to the directory object.
 * \param _path	Pointer to pointer to the segment in the path string.
 *
 * \return Status
 *
 */
static FRESULT create_name(DIR *_dj, const TCHAR **_path)
{
	#if _USE_LFN	/* LFN configuration */
		BYTE _b, _cf;
		WCHAR _w, *_lfn;
		UINT i, _ni, _si, _di;
		const TCHAR *_p;
		
		/* Create LFN in Unicode */
		for (_p = *_path; *_p == '/' || *_p == '\\'; _p++) ;	/* Strip duplicated separator */
		_lfn = _dj->lfn;
		_si = _di = 0;
		for (;;) {
			_w = _p[_si++];					/* Get a character */
			if (_w < ' ' || _w == '/' || _w == '\\') break;	/* Break on end of segment */
			if (_di >= _MAX_LFN)				/* Reject too long name */
				return FR_INVALID_NAME;
			#if !_LFN_UNICODE
				_w &= 0xFF;
				if (IsDBCS1(_w)) {				/* Check if it is a DBC 1st byte (always false on SBCS cfg) */
					_b = (BYTE)_p[_si++];		/* Get 2nd byte */
					if (!IsDBCS2(_b))
						return FR_INVALID_NAME;	/* Reject invalid sequence */
					_w = (_w << 8) + _b;			/* Create a DBC */
				}
				_w = ff_convert(_w, 1);			/* Convert ANSI/OEM to Unicode */
				if (!_w) return FR_INVALID_NAME;	/* Reject invalid code */
			#endif /* _LFN_UNICODE */
			if (_w < 0x80 && chk_chr("\"*:<>\?|\x7F", _w)) /* Reject illegal chars for LFN */
				return FR_INVALID_NAME;
			_lfn[_di++] = _w;					/* Store the Unicode char */
		}
		*_path = &_p[_si];						/* Return pointer to the next segment */
		_cf = (_w < ' ') ? NS_LAST : 0;		/* Set last segment flag if end of path */
		
		#if _FS_RPATH
			if ((_di == 1 && _lfn[_di - 1] == '.') || /* Is this a dot entry? */
				(_di == 2 && _lfn[_di - 1] == '.' && _lfn[_di - 2] == '.')) {
				_lfn[_di] = 0;
				for (i = 0; i < 11; i++)
					_dj->fn[i] = (i < _di) ? '.' : ' ';
				_dj->fn[i] = _cf | NS_DOT;		/* This is a dot entry */
				return FR_OK;
			}
		#endif /* _FS_RPATH */
		while (_di) {						/* Strip trailing spaces and dots */
			_w = _lfn[_di - 1];
			if (_w != ' ' && _w != '.') break;
			_di--;
		}
		if (!_di) return FR_INVALID_NAME;	/* Reject null string */
		
		_lfn[_di] = 0;						/* LFN is created */
		
		/* Create SFN in directory form */
		mem_set(_dj->fn, ' ', 11);
		for (_si = 0; _lfn[_si] == ' ' || _lfn[_si] == '.'; _si++) ;	/* Strip leading spaces and dots */
		if (_si) _cf |= NS_LOSS | NS_LFN;
		while (_di && _lfn[_di - 1] != '.') _di--;	/* Find extension (di<=si: no extension) */
		
		_b = i = 0; _ni = 8;
		for (;;) {
			_w = _lfn[_si++];					/* Get an LFN char */
			if (!_w) break;					/* Break on end of the LFN */
			if (_w == ' ' || (_w == '.' && _si != _di)) {	/* Remove spaces and dots */
				_cf |= NS_LOSS | NS_LFN; continue;
			}
			
			if (i >= _ni || _si == _di) {		/* Extension or end of SFN */
				if (_ni == 11) {				/* Long extension */
					_cf |= NS_LOSS | NS_LFN; break;
				}
				if (_si != _di) _cf |= NS_LOSS | NS_LFN;	/* Out of 8.3 format */
				if (_si > _di) break;			/* No extension */
				_si = _di; i = 8; _ni = 11;	/* Enter extension section */
				_b <<= 2; continue;
			}
			
			if (_w >= 0x80) {				/* Non ASCII char */
				#ifdef _EXCVT
					_w = ff_convert(_w, 0);		/* Unicode -> OEM code */
					if (_w) _w = ExCvt[_w - 0x80];	/* Convert extended char to upper (SBCS) */
				#else
					_w = ff_convert(ff_wtoupper(_w), 0);	/* Upper converted Unicode -> OEM code */
				#endif
				_cf |= NS_LFN;				/* Force create LFN entry */
			}
			
			if (_DF1S && _w >= 0x100) {		/* Double byte char (always false on SBCS cfg) */
				if (i >= _ni - 1) {
					_cf |= NS_LOSS | NS_LFN; i = _ni; continue;
				}
				_dj->fn[i++] = (BYTE)(_w >> 8);
			} 
			else {						/* Single byte char */
				if (!_w || chk_chr("+,;=[]", _w)) {	/* Replace illegal chars for SFN */
					_w = '_'; _cf |= NS_LOSS | NS_LFN;/* Lossy conversion */
				}
				else {
					if (IsUpper(_w)) {		/* ASCII large capital */
						_b |= 2;
					}
					else {
						if (IsLower(_w)) {	/* ASCII small capital */
							_b |= 1; _w -= 0x20;
						}
					}
				}
			}
			_dj->fn[i++] = (BYTE)_w;
		}
		
		if (_dj->fn[0] == DDE) _dj->fn[0] = NDDE;	/* If the first char collides with deleted mark, replace it with 0x05 */
		
		if (_ni == 8) _b <<= 2;
		if ((_b & 0x0C) == 0x0C || (_b & 0x03) == 0x03)	/* Create LFN entry when there are composite capitals */
			_cf |= NS_LFN;
		if (!(_cf & NS_LFN)) {						/* When LFN is in 8.3 format without extended char, NT flags are created */
			if ((_b & 0x03) == 0x01) _cf |= NS_EXT;	/* NT flag (Extension has only small capital) */
			if ((_b & 0x0C) == 0x04) _cf |= NS_BODY;	/* NT flag (Filename has only small capital) */
		}
		
		_dj->fn[NS] = _cf;	/* SFN is created */
		
		return FR_OK;
		
	/* Non-LFN configuration */
	#else /* _USE_LFN */
		BYTE _b, _c, d, *_sfn;
		UINT _ni, _si, _i;
		const char *_p;
		
		/* Create file name in directory form */
		for (_p = *_path; *_p == '/' || *_p == '\\'; _p++) ;	/* Strip duplicated separator */
		_sfn = dj->fn;
		mem_set(_sfn, ' ', 11);
		_si = i = _b = 0; _ni = 8;
		
		#if _FS_RPATH
			if (_p[_si] == '.') { /* Is this a dot entry? */
				for (;;) {
					_c = (BYTE)_p[_si++];
					if (_c != '.' || _si >= 3) break;
					_sfn[i++] = _c;
				}
				if (_c != '/' && _c != '\\' && _c > ' ') return FR_INVALID_NAME;
				*_path = &_p[_si];									/* Return pointer to the next segment */
				_sfn[NS] = (_c <= ' ') ? NS_LAST | NS_DOT : NS_DOT;	/* Set last segment flag if end of path */
				return FR_OK;
			}
		#endif /* _FS_RPATH */
		
		for (;;) {
			_c = (BYTE)_p[_si++];
			if (_c <= ' ' || _c == '/' || _c == '\\') break;	/* Break on end of segment */
			if (_c == '.' || i >= _ni) {
				if (_ni != 8 || _c != '.') return FR_INVALID_NAME;
				i = 8; _ni = 11;
				_b <<= 2; continue;
			}
			if (_c >= 0x80) {				/* Extended char? */
				_b |= 3;						/* Eliminate NT flag */
				#ifdef _EXCVT
					_c = ExCvt[_c - 0x80];		/* To upper extended chars (SBCS cfg) */
				#else
					#if !_DF1S
						return FR_INVALID_NAME;		/* Reject extended chars (ASCII cfg) */
					#endif
				#endif
			}
			if (IsDBCS1(_c)) {				/* Check if it is a DBC 1st byte (always false on SBCS cfg) */
				_d = (BYTE)_p[_si++];			/* Get 2nd byte */
				if (!IsDBCS2(_d) || i >= _ni - 1)	/* Reject invalid DBC */
					return FR_INVALID_NAME;
				_sfn[i++] = _c;
				_sfn[i++] = _d;
			}
			else {						/* Single byte code */
				if (chk_chr("\"*+,:;<=>\?[]|\x7F", _c))	/* Reject illegal chrs for SFN */
					return FR_INVALID_NAME;
				if (IsUpper(_c)) {			/* ASCII large capital? */
					_b |= 2;
				}
				else {
					if (IsLower(_c)) {		/* ASCII small capital? */
						_b |= 1; _c -= 0x20;
					}
				}
				_sfn[i++] = _c;
			}
		}
		*_path = &_p[_si];						/* Return pointer to the next segment */
		_c = (_c <= ' ') ? NS_LAST : 0;		/* Set last segment flag if end of path */
		
		if (!i) return FR_INVALID_NAME;		/* Reject nul string */
		if (_sfn[0] == DDE) _sfn[0] = NDDE;	/* When first char collides with DDE, replace it with 0x05 */
		
		if (_ni == 8) _b <<= 2;
		if ((_b & 0x03) == 0x01) _c |= NS_EXT;	/* NT flag (Name extension has only small capital) */
		if ((_b & 0x0C) == 0x04) _c |= NS_BODY;	/* NT flag (Name body has only small capital) */
		
		_sfn[NS] = _c;		/* Store NT flag, File name is created */
		
		return FR_OK;
	#endif /* _USE_LFN */
}


#if _FS_MINIMIZE <= 1 || _FS_RPATH >= 2

/** \brief Get file information from directory entry.
 *
 * \param _dj	Pointer to the directory object.
 * \param _fno	 Pointer to the file information to be filled.
 *
 */
static void get_fileinfo(DIR *_dj, FILINFO *_fno)
{
	UINT i;
	BYTE _nt, *_dir;
	TCHAR *_p, _c;


	_p = _fno->fname;
	if (_dj->sect) {
		_dir = _dj->dir;
		_nt = _dir[DIR_NTres];		/* NT flag */
		for (i = 0; i < 8; i++) {	/* Copy name body */
			_c = _dir[i];
			if (_c == ' ') break;
			if (_c == NDDE) _c = (TCHAR)DDE;
			if (_USE_LFN && (_nt & NS_BODY) && IsUpper(_c)) _c += 0x20;
			#if _LFN_UNICODE
				if (IsDBCS1(_c) && i < 7 && IsDBCS2(_dir[i + 1]))
					_c = (_c << 8) | _dir[++i];
				_c = ff_convert(_c, 1);
				if (!_c) _c = '?';
			#endif
			*_p++ = _c;
		}
		if (_dir[8] != ' ') {		/* Copy name extension */
			*_p++ = '.';
			for (i = 8; i < 11; i++) {
				_c = _dir[i];
				if (_c == ' ') break;
				if (_USE_LFN && (_nt & NS_EXT) && IsUpper(_c)) _c += 0x20;
				
				#if _LFN_UNICODE
					if (IsDBCS1(_c) && i < 10 && IsDBCS2(dir[i+1]))
						_c = (_c << 8) | _dir[++i];
					_c = ff_convert(_c, 1);
					if (!_c) _c = '?';
				#endif
				*_p++ = _c;
			}
		}
		_fno->fattrib = _dir[DIR_Attr];				/* Attribute */
		_fno->fsize = LD_DWORD(_dir + DIR_FileSize);	/* Size */
		_fno->fdate = LD_WORD(_dir + DIR_WrtDate);		/* Date */
		_fno->ftime = LD_WORD(_dir + DIR_WrtTime);		/* Time */
	}
	*_p = 0;		/* Terminate SFN str by a \0 */

	#if _USE_LFN
		if (_fno->lfname && _fno->lfsize) {
			TCHAR *_tp = _fno->lfname;
			WCHAR _w, *_lfn;
			
			i = 0;
			if (_dj->sect && _dj->lfn_idx != 0xFFFF) {/* Get LFN if available */
				_lfn = _dj->lfn;
				while ((_w = *_lfn++) != 0) {			/* Get an LFN char */
				#if !_LFN_UNICODE
					_w = ff_convert(_w, 0);			/* Unicode -> OEM conversion */
					if (!_w) { i = 0; break; }		/* Could not convert, no LFN */
					if (_DF1S && _w >= 0x100)		/* Put 1st byte if it is a DBC (always false on SBCS cfg) */
						_tp[i++] = (TCHAR)(_w >> 8);
				#endif
				if (i >= _fno->lfsize - 1) { i = 0; break; }	/* Buffer overflow, no LFN */
				_tp[i++] = (TCHAR)_w;
			}
		}
		_tp[i] = 0;	/* Terminate the LFN str by a \0 */
	}
	#endif
}
#endif /* _FS_MINIMIZE <= 1 || _FS_RPATH >= 2*/


/** \brief Follow a file path.
 *
 * \param _dj	Directory object to return last directory and found object.
 * \param _path	Full-path string to find a file or directory.
 *
 * \return Status FR_OK(0): successful, !=0: error code.
 *
 */

static FRESULT follow_path(DIR *_dj, const TCHAR *_path)
{
	FRESULT _res;
	BYTE *_dir, _ns;
	
	#if _FS_RPATH
		if (*_path == '/' || *_path == '\\') { /* There is a heading separator */
			_path++;
			_dj->sclust = 0;		/* Strip it and start from the root dir */
		} 
		else {							/* No heading separator */
			_dj->sclust = _dj->fs->cdir;	/* Start from the current dir */
		}
	#else /* _FS_RPATH */
		if (*_path == '/' || *_path == '\\')	/* Strip heading separator if exist */
			_path++;
		_dj->sclust = 0;						/* Start from the root dir */
	#endif /* _FS_RPATH */

	if ((UINT)*_path < ' ') {			/* Null path means the start directory itself */
		_res = dir_sdi(_dj, 0);
		_dj->dir = 0;
	} 
	else {							/* Follow path */
		for (;;) {
			_res = create_name(_dj, &_path);	/* Get a segment */
			if (_res != FR_OK) break;
			_res = dir_find(_dj);				/* Find it */
			_ns = *(_dj->fn + NS);
			if (_res != FR_OK) {				/* Failed to find the object */
				if (_res != FR_NO_FILE) break;	/* Abort if any hard error occurred */
				/* Object not found */
				if (_FS_RPATH && (_ns & NS_DOT)) {	/* If dot entry is not exit */
					_dj->sclust = 0; _dj->dir = 0;	/* It is the root dir */
					_res = FR_OK;
					if (!(_ns & NS_LAST)) continue;
				}
				else {							/* Could not find the object */
					if (!(_ns & NS_LAST)) _res = FR_NO_PATH;
				}
				break;
			}
			if (_ns & NS_LAST) break;			/* Last segment match. Function completed. */
			_dir = _dj->dir;					/* There is next segment. Follow the sub directory */
			if (!(_dir[DIR_Attr] & AM_DIR)) {	/* Cannot follow because it is a file */
				_res = FR_NO_PATH; break;
			}
			_dj->sclust = ld_clust(_dj->fs, _dir);
		}
	}

	return _res;
}


/** \brief Load a sector and check if it is an FAT Volume Boot Record.
 *
 * \param _fs	File system object.
 * \param _sect	Sector# (lba) to check if it is an FAT boot record or not.
 *
 * \return Result. 0:FAT-VBR, 1:Any BR but not FAT, 2:Not a BR, 3:Disk error.
 *
 */
static BYTE check_fs(FATFS *_fs, DWORD _sect)
{
	if (disk_read(_fs->drv, _fs->win, _sect, 1) != RES_OK)	/* Load boot record */
		return 3;
	if (LD_WORD(&_fs->win[BS_55AA]) != 0xAA55)		/* Check record signature (always placed at offset 510 even if the sector size is >512) */
		return 2;

	if ((LD_DWORD(&_fs->win[BS_FilSysType]) & 0xFFFFFF) == 0x544146)	/* Check "FAT" string */
		return 0;
	if ((LD_DWORD(&_fs->win[BS_FilSysType32]) & 0xFFFFFF) == 0x544146)
		return 0;

	return 1;
}


/** \brief Check if the file system object is valid or not.
 *
 * \param path	Pointer to pointer to the path name (drive number).
 * \param rfs	Pointer to pointer to the found file system object.
 * \param wmode	!=0: Check write protection for write access
 *
 * \return FR_OK(0): successful, !=0: any error occurred.
 *
 */
static FRESULT chk_mounted(const TCHAR **_path, FATFS **_rfs, BYTE _wmode)
{
	BYTE _fmt, _b, _pi, *_tbl;
	UINT _vol;
	DSTATUS _stat;
	DWORD _bsect, _fasize, _tsect, _sysect, _nclst, _szbfat;
	WORD _nrsv;
	const TCHAR *_p = *_path;
	FATFS *_fs;
	
	/* Get logical drive number from the path name */
	_vol = _p[0] - '0';
	/* Is there a drive number? */
	if (_vol <= 9 && _p[1] == ':') {
		/* Found a drive number, get and strip it */
		/* Return pointer to the path name */
		_p += 2; *_path = _p;
	}
	/* No drive number, use default drive */
	else {
		#if _FS_RPATH
			/* Use current drive */
			_vol = CurrVol;
		#else
			/* Use drive 0 */
			_vol = 0;
		#endif
	}

	/* Check if the file system object is valid or not */
	*_rfs = 0;
	/* Is the drive number valid? */
	if (_vol >= _VOLUMES) {
		FATFS_DEBUGF("Drive invalid: Vol %d\n", _vol);
		return FR_INVALID_DRIVE;
	}
	/* Get corresponding file system object */
	_fs = FatFs[_vol];

	/* Is the file system object available? */
	if(!_fs) {
		FATFS_DEBUGF("File system not available\n");
		return FR_NOT_ENABLED;
	}

	/* Lock volume */
	ENTER_FF(_fs);

	/* Return pointer to the corresponding file system object */
	*_rfs = _fs;
	/* If the volume has been mounted */
	if (_fs->fs_type) {
		_stat = disk_status(_fs->drv);
		/* and the physical drive is kept initialized (has not been changed), */
		if (!(_stat & STA_NOINIT)) {
			/* Check write protection if needed */
			if (!_FS_READONLY && _wmode && (_stat & STA_PROTECT)) {
				FATFS_DEBUGF("Drive is write protected.\n");
				return FR_WRITE_PROTECTED;
			}

			/* The file system object is valid */
			FATFS_DEBUGF("File system is valid.\n");
			return FR_OK;
		}
	}

	/* The file system object is not valid. */
	/* Following code attempts to mount the volume.
	 * (analyze BPB and initialize the fs object) */

	/* Clear the file system object */
	_fs->fs_type = 0;
	/* Bind the logical drive and a physical drive */
	_fs->drv = LD2PD(_vol);
	/* Initialize the physical drive */
	_stat = disk_initialize(_fs->drv);
	FATFS_DEBUGF("Initialize drive: %d status: %d\n", _fs->drv, _stat);

	/* Check if the initialization succeeded */
	if (_stat & STA_NOINIT)	{
		/* Failed to initialize due to no medium or hard error */
		return FR_NOT_READY;
	}
	if (!_FS_READONLY && _wmode && (_stat & STA_PROTECT)) {
		/* Check disk write protection if needed */
		return FR_WRITE_PROTECTED;
	}

	/* Get disk sector size (variable sector size cfg only) */
	#if _MAX_SS != 512
		DRESULT _io_status;
		_io_status = disk_ioctl(_fs->drv, GET_SECTOR_SIZE, &_fs->ssize);
		if (_io_status != RES_OK) {
			return FR_DISK_ERR;
		}
	#endif
	
	/* Search FAT partition on the drive. Supports only generic partitions, FDISK and SFD. */
	/* Load sector 0 and check if it is an FAT-VBR (in SFD) */
	_fmt = check_fs(_fs, _bsect = 0);
	FATFS_DEBUGF("Check 1 FAT format: %d\n", _fmt);
	/* Force non-SFD if the volume is forced partition */
	if (LD2PT(_vol) && !_fmt) _fmt = 1;
	/* Not an FAT-VBR, the physical drive can be partitioned */
	if (_fmt == 1) {
		/* Check the partition listed in the partition table */
		_pi = LD2PT(_vol);
		if (_pi) _pi--;
		/* Partition table */
		_tbl = &_fs->win[MBR_Table + _pi * SZ_PTE];
		/* Is the partition existing? */
		if (_tbl[4]) {
			/* Partition offset in LBA */
			_bsect = LD_DWORD(&_tbl[8]);
			/* Check the partition */
			_fmt = check_fs(_fs, _bsect);
			FATFS_DEBUGF("Check 2 FAT format: %d\n", _fmt);
		}
	}
	if (_fmt == 3) {
		return FR_DISK_ERR;
	}
	if (_fmt) {
		/* No FAT volume is found */
		return FR_NO_FILESYSTEM;
	}
	/* An FAT volume is found. Following code initializes the file system object */

	/* (BPB_BytsPerSec must be equal to the physical sector size) */
	if (LD_WORD(_fs->win + BPB_BytsPerSec) != SS(_fs)) {
		return FR_NO_FILESYSTEM;
	}

	/* Number of sectors per FAT */
	_fasize = LD_WORD(_fs->win + BPB_FATSz16);
	if (!_fasize) _fasize = LD_DWORD(_fs->win + BPB_FATSz32);
	_fs->fsize = _fasize;

	/* Number of FAT copies */
	_fs->n_fats = _b = _fs->win[BPB_NumFATs];
	/* (Must be 1 or 2) */
	if (_b != 1 && _b != 2) {
		return FR_NO_FILESYSTEM;
	}
	/* Number of sectors for FAT area */
	_fasize *= _b;

	/* Number of sectors per cluster */
	_fs->csize = _b = _fs->win[BPB_SecPerClus];
	/* (Must be power of 2) */
	if (!_b || (_b & (_b - 1))) {
		return FR_NO_FILESYSTEM;
	}

	/* Number of root directory entries */
	_fs->n_rootdir = LD_WORD(_fs->win + BPB_RootEntCnt);
	/* (BPB_RootEntCnt must be sector aligned) */
	if (_fs->n_rootdir % (SS(_fs) / SZ_DIR)) {
		return FR_NO_FILESYSTEM;
	}

	/* Number of sectors on the volume */
	_tsect = LD_WORD(_fs->win + BPB_TotSec16);
	if (!_tsect) _tsect = LD_DWORD(_fs->win + BPB_TotSec32);

	/* Number of reserved sectors */
	_nrsv = LD_WORD(_fs->win + BPB_RsvdSecCnt);
	/* (BPB_RsvdSecCnt must not be 0) */
	if (!_nrsv) {
		return FR_NO_FILESYSTEM;
	}
	/* Determine the FAT sub type */
	/* RSV+FAT+DIR */
	_sysect = _nrsv + _fasize + _fs->n_rootdir / (SS(_fs) / SZ_DIR);
	/* (Invalid volume size) */
	if (_tsect < _sysect) {
		return FR_NO_FILESYSTEM;
	}
	/* Number of clusters */
	_nclst = (_tsect - _sysect) / _fs->csize;
	/* (Invalid volume size) */
	if (!_nclst) {
		return FR_NO_FILESYSTEM;
	}
	_fmt = FS_FAT12;
	if (_nclst >= MIN_FAT16) _fmt = FS_FAT16;
	if (_nclst >= MIN_FAT32) _fmt = FS_FAT32;

	/* Boundaries and Limits */
	/* Number of FAT entries */
	_fs->n_fatent = _nclst + 2;
	/* Volume start sector */
	_fs->volbase = _bsect;
	/* FAT start sector */
	_fs->fatbase = _bsect + _nrsv;
	/* Data start sector */
	_fs->database = _bsect + _sysect;
	if (_fmt == FS_FAT32) {
		/* (BPB_RootEntCnt must be 0) */
		if (_fs->n_rootdir) {
			return FR_NO_FILESYSTEM;
		}
		/* Root directory start cluster */
		_fs->dirbase = LD_DWORD(_fs->win + BPB_RootClus);
		/* (Required FAT size) */
		_szbfat = _fs->n_fatent * 4;
	}
	else {
		/* (BPB_RootEntCnt must not be 0) */
		if (!_fs->n_rootdir)	{
			return FR_NO_FILESYSTEM;
		}
		/* Root directory start sector */
		_fs->dirbase = _fs->fatbase + _fasize;
		/* (Required FAT size) */
		_szbfat = (_fmt == FS_FAT16) ? _fs->n_fatent * 2 : _fs->n_fatent * 3 / 2 + (_fs->n_fatent & 1);
	}
	/* (BPB_FATSz must not be less than required) */
	if (_fs->fsize < (_szbfat + (SS(_fs) - 1)) / SS(_fs)) {
		return FR_NO_FILESYSTEM;
	}

	#if !_FS_READONLY
		/* Initialize cluster allocation information */
		_fs->free_clust = 0xFFFFFFFF;
		_fs->last_clust = 0;
		
		/* Get fsinfo if available */
		if (_fmt == FS_FAT32) {
			_fs->fsi_flag = 0;
			_fs->fsi_sector = _bsect + LD_WORD(_fs->win + BPB_FSInfo);
			if (disk_read(_fs->drv, _fs->win, _fs->fsi_sector, 1) == RES_OK &&
				LD_WORD(_fs->win + BS_55AA) == 0xAA55 &&
				LD_DWORD(_fs->win + FSI_LeadSig) == 0x41615252 &&
				LD_DWORD(_fs->win + FSI_StrucSig) == 0x61417272) {
					_fs->last_clust = LD_DWORD(_fs->win + FSI_Nxt_Free);
					_fs->free_clust = LD_DWORD(_fs->win + FSI_Free_Count);
			}
		}
	#endif /* _FS_READONLY */
	
	/* FAT sub-type */
	_fs->fs_type = _fmt;
	/* File system mount ID */
	_fs->id = ++Fsid;
	/* Invalidate sector cache */
	_fs->winsect = 0;
	_fs->wflag = 0;

	#if _FS_RPATH
		/* Current directory (root dir) */
		_fs->cdir = 0;
	#endif

	#if _FS_LOCK
		/* Clear file lock semaphores */
		clear_lock(_fs);
	#endif

	return FR_OK;
}

/** \brief Check if the file/dir object is valid or not.
 *
 * \param _obj	Pointer to the object FIL/DIR to check validity.
 *
 * \return Status. FR_OK(0): The object is valid, !=0: Invalid.
 */
static FRESULT validate(void *_obj)
{
	FIL *_fil = (FIL*)_obj;	/* Assuming offset of fs and id in the FIL/DIR is identical */


	if (!_fil || !_fil->fs || !_fil->fs->fs_type || _fil->fs->id != _fil->id)
		return FR_INVALID_OBJECT;

	ENTER_FF(_fil->fs);		/* Lock file system */

	if (disk_status(_fil->fs->drv) & STA_NOINIT)
		return FR_NOT_READY;

	return FR_OK;
}




/*--------------------------------------------------------------------------

   Public Functions

--------------------------------------------------------------------------*/

FRESULT f_mount(BYTE _vol, FATFS *_fs)
{
	FATFS *_rfs;
	
	if (_vol >= _VOLUMES) {		/* Check if the drive number is valid */
		return FR_INVALID_DRIVE;
	}
	_rfs = FatFs[_vol];			/* Get current fs object */

	if (_rfs) {
	#if _FS_LOCK
		clear_lock(_rfs);
	#endif
	
	#if _FS_REENTRANT				/* Discard sync object of the current volume */
		if (!ff_del_syncobj(_rfs->sobj)) {
			return FR_INT_ERR;
		}
	#endif
		_rfs->fs_type = 0;		/* Clear old fs object */
	}

	if (_fs) {
		_fs->fs_type = 0;		/* Clear new fs object */
		#if _FS_REENTRANT				/* Create sync object for the new volume */
			if (!ff_cre_syncobj(_vol, &_fs->sobj)) {
				return FR_INT_ERR;
			}
		#endif
	}
	FatFs[_vol] = _fs;			/* Register new fs object */
	
	return FR_OK;
}


FRESULT f_open(FIL *_fp, const TCHAR *_path, BYTE _mode)
{
	FRESULT _res;
	DIR _dj;
	BYTE *_dir;
	DEF_NAMEBUF;
	
	if (!_fp) {
		return FR_INVALID_OBJECT;
	}

	/* Clear file object */
	_fp->fs = 0;

	#if !_FS_READONLY
		_mode &= (FA_READ | FA_WRITE | FA_CREATE_ALWAYS | FA_OPEN_ALWAYS | FA_CREATE_NEW);
		_res = chk_mounted(&_path, &_dj.fs, (BYTE)(_mode & ~FA_READ));
	#else
		_mode &= FA_READ;
		_res = chk_mounted(&_path, &_dj.fs, 0);
	#endif /* _FS_READONLY */
	
	if (_res == FR_OK) {
		INIT_BUF(_dj);
		/* Follow the file path */
		_res = follow_path(&_dj, _path);
		_dir = _dj.dir;
		
		#if !_FS_READONLY	/* R/W configuration */
			if (_res == FR_OK) {
				if (!_dir)	/* Current dir itself */
					_res = FR_INVALID_NAME;
				#if _FS_LOCK
				else
					_res = chk_lock(&_dj, (_mode & ~FA_READ) ? 1 : 0);
				#endif /* _FS_LOCK */
			}
			
			/* Create or Open a file */
			if (_mode & (FA_CREATE_ALWAYS | FA_OPEN_ALWAYS | FA_CREATE_NEW)) {
				DWORD _dw, _cl;
				if (_res != FR_OK) {					/* No file, create new */
					if (_res == FR_NO_FILE)			/* There is no file to open, create a new entry */
						#if _FS_LOCK
							_res = enq_lock() ? dir_register(&_dj) : FR_TOO_MANY_OPEN_FILES;
						#else
							_res = dir_register(&_dj);
						#endif /* _FS_LOCK */
					_mode |= FA_CREATE_ALWAYS;		/* File is created */
					_dir = _dj.dir;					/* New entry */
				}
				else {								/* Any object is already existing */
					if (_dir[DIR_Attr] & (AM_RDO | AM_DIR)) {	/* Cannot overwrite it (R/O or DIR) */
						_res = FR_DENIED;
					} 
					else {
						if (_mode & FA_CREATE_NEW)	/* Cannot create as new file */
							_res = FR_EXIST;
					}
				}
				
				if (_res == FR_OK && (_mode & FA_CREATE_ALWAYS)) {	/* Truncate it if overwrite mode */
					_dw = get_fattime();					/* Created time */
					ST_DWORD(_dir + DIR_CrtTime, _dw);
					_dir[DIR_Attr] = 0;					/* Reset attribute */
					ST_DWORD(_dir + DIR_FileSize, 0);		/* size = 0 */
					_cl = ld_clust(_dj.fs, _dir);			/* Get start cluster */
					st_clust(_dir, 0);					/* cluster = 0 */
					_dj.fs->wflag = 1;
					if (_cl) {							/* Remove the cluster chain if exist */
						_dw = _dj.fs->winsect;
						_res = remove_chain(_dj.fs, _cl);
						if (_res == FR_OK) {
							_dj.fs->last_clust = _cl - 1;	/* Reuse the cluster hole */
							_res = move_window(_dj.fs, _dw);
						}
					}
				}
			}
			else {	/* Open an existing file */
				if (_res == FR_OK) {						/* Follow succeeded */
					if (_dir[DIR_Attr] & AM_DIR) {		/* It is a directory */
						_res = FR_NO_FILE;
					} 
					else {
						if ((_mode & FA_WRITE) && (_dir[DIR_Attr] & AM_RDO)) /* R/O violation */
							_res = FR_DENIED;
					}
				}
			}
			
			if (_res == FR_OK) {
				/* Set file change flag if created or overwritten */
				if (_mode & FA_CREATE_ALWAYS) _mode |= FA__WRITTEN;
				
				_fp->dir_sect = _dj.fs->winsect;	/* Pointer to the directory entry */
				_fp->dir_ptr = _dir;
				
				#if _FS_LOCK
					_fp->lockid = inc_lock(&_dj, (_mode & ~FA_READ) ? 1 : 0);
					if (!_fp->lockid) _res = FR_INT_ERR;
				#endif /* _FS_LOCK */
			}
		/* R/O configuration */
		#else /* _FS_READONLY */
			if (_res == FR_OK) {					/* Follow succeeded */
				_dir = _dj.dir;
				if (!_dir) {						/* Current dir itself */
					_res = FR_INVALID_NAME;
				} 
				else {
					if (_dir[DIR_Attr] & AM_DIR)	/* It is a directory */
						_res = FR_NO_FILE;
				}
			}
		#endif /* _FS_READONLY */
		
		FREE_BUF();

		if (_res == FR_OK) {
			_fp->flag = _mode;					/* File access mode */
			_fp->sclust = ld_clust(_dj.fs, _dir);	/* File start cluster */
			_fp->fsize = LD_DWORD(_dir + DIR_FileSize);	/* File size */
			_fp->fptr = 0;						/* File pointer */
			_fp->dsect = 0;
			#if _USE_FASTSEEK
				_fp->cltbl = 0;						/* Normal seek mode */
			#endif
				_fp->fs = _dj.fs;
				_fp->id = _dj.fs->id;	/* Validate file object */
		}
	}

	unlock_fs(_dj.fs, _res);
	return _res;
}


FRESULT f_read(FIL *_fp, void *_buff, UINT _btr, UINT *_br)
{
	FRESULT _res;
	DRESULT _io_status;
	DWORD _clst, _sect, _remain;
	UINT _rcnt, _cc;
	BYTE _csect, *_rbuff = (BYTE*)_buff;


	*_br = 0;	/* Clear read byte counter */

	_res = validate(_fp);			/* Check validity */
	if (_res != FR_OK) {
		LEAVE_FF(_fp->fs, _res);
	}
	if (_fp->flag & FA__ERROR) {	/* Aborted file? */
		LEAVE_FF(_fp->fs, FR_INT_ERR);
	}
	if (!(_fp->flag & FA_READ)) {	/* Check access mode */
		LEAVE_FF(_fp->fs, FR_DENIED);
	}
	_remain = _fp->fsize - _fp->fptr;
	if (_btr > _remain) _btr = (UINT)_remain;		/* Truncate btr by remaining bytes */

	for ( ;  _btr;								/* Repeat until all data read */
		_rbuff += _rcnt, _fp->fptr += _rcnt, *_br += _rcnt, _btr -= _rcnt) {
		if ((_fp->fptr % SS(_fp->fs)) == 0) {		/* On the sector boundary? */
			_csect = (BYTE)(_fp->fptr / SS(_fp->fs) & (_fp->fs->csize - 1));	/* Sector offset in the cluster */
			if (!_csect) {						/* On the cluster boundary? */
				if (_fp->fptr == 0) {			/* On the top of the file? */
					_clst = _fp->sclust;			/* Follow from the origin */
				}
				else {						/* Middle or end of the file */
					#if _USE_FASTSEEK
						if (_fp->cltbl)
							_clst = clmt_clust(_fp, _fp->fptr);	/* Get cluster# from the CLMT */
						else
					#endif
							_clst = get_fat(_fp->fs, _fp->clust);	/* Follow cluster chain on the FAT */
				}
				if (_clst < 2) {
					ABORT(_fp->fs, FR_INT_ERR);
				}
				if (_clst == 0xFFFFFFFF) {
					ABORT(_fp->fs, FR_DISK_ERR);
				}
				_fp->clust = _clst;				/* Update current cluster */
			}
			_sect = clust2sect(_fp->fs, _fp->clust);	/* Get current sector */
			if (!_sect) {
				ABORT(_fp->fs, FR_INT_ERR);
			}
			_sect += _csect;
			_cc = _btr / SS(_fp->fs);				/* When remaining bytes >= sector size, */
			if (_cc) {							/* Read maximum contiguous sectors directly */
				if (_csect + _cc > _fp->fs->csize)	/* Clip at cluster boundary */
					_cc = _fp->fs->csize - _csect;
				_io_status = disk_read(_fp->fs->drv, _rbuff, _sect, (BYTE)_cc);
				if (_io_status != RES_OK) {
					ABORT(_fp->fs, FR_DISK_ERR);
				}
				
				#if !_FS_READONLY && _FS_MINIMIZE <= 2			/* Replace one of the read sectors with cached data if it contains a dirty sector */
					#if _FS_TINY
						if (_fp->fs->wflag && _fp->fs->winsect - _sect < _cc)
							mem_cpy(_rbuff + ((_fp->fs->winsect - _sect) * SS(_fp->fs)), _fp->fs->win, SS(_fp->fs));
					#else
						if ((_fp->flag & FA__DIRTY) && _fp->dsect - _sect < _cc)
							mem_cpy(_rbuff + ((_fp->dsect - _sect) * SS(_fp->fs)), _fp->buf, SS(_fp->fs));
					#endif
				#endif
				_rcnt = SS(_fp->fs) * _cc;			/* Number of bytes transferred */
				continue;
			}
			
			#if !_FS_TINY
				if (_fp->dsect != _sect) {			/* Load data sector if not in cache */
					#if !_FS_READONLY
						if (_fp->flag & FA__DIRTY) {		/* Write-back dirty sector cache */
							_io_status = disk_write(_fp->fs->drv, _fp->buf, _fp->dsect, 1);
							if (_io_status != RES_OK) {
								ABORT(_fp->fs, FR_DISK_ERR);
							}
							_fp->flag &= ~FA__DIRTY;
						}
					#endif
					
					_io_status = disk_read(_fp->fs->drv, _fp->buf, _sect, 1);	/* Fill sector cache */
					if (_io_status != RES_OK) {
						ABORT(_fp->fs, FR_DISK_ERR);
					}
				}
			#endif
			_fp->dsect = _sect;
		}
		_rcnt = SS(_fp->fs) - ((UINT)_fp->fptr % SS(_fp->fs));	/* Get partial sector data from sector buffer */
		if (_rcnt > _btr) _rcnt = _btr;
		
		#if _FS_TINY
			_res = move_window(_fp->fs, _fp->dsect);	/* Move sector window */
			if (_res) {
				ABORT(_fp->fs, FR_DISK_ERR);
			}
			mem_cpy(_rbuff, &_fp->fs->win[_fp->fptr % SS(_fp->fs)], _rcnt);	/* Pick partial sector */
		#else
			mem_cpy(_rbuff, &_fp->buf[_fp->fptr % SS(_fp->fs)], _rcnt);	/* Pick partial sector */
		#endif
	}

	unlock_fs(_fp->fs, FR_OK);
	return FR_OK;
}




#if !_FS_READONLY

FRESULT f_write(FIL *_fp, const void *_buff, UINT _btw, UINT *_bw)
{
	FRESULT _res;
	DRESULT _io_status;
	DWORD _clst, _sect;
	UINT _wcnt, _cc;
	const BYTE *_wbuff = (const BYTE*)_buff;
	BYTE _csect;

	*_bw = 0;	/* Clear write byte counter */

	_res = validate(_fp);	/* Check validity */
	if (_res != FR_OK) {
		LEAVE_FF(_fp->fs, _res);
	}
	if (_fp->flag & FA__ERROR) {	/* Aborted file? */
		LEAVE_FF(_fp->fs, FR_INT_ERR);
	}
	if (!(_fp->flag & FA_WRITE)) {	/* Check access mode */
		LEAVE_FF(_fp->fs, FR_DENIED);
	}
	if ((DWORD)(_fp->fsize + _btw) < _fp->fsize) _btw = 0;	/* File size cannot reach 4GB */

	for ( ;  _btw;							/* Repeat until all data written */
		_wbuff += _wcnt, _fp->fptr += _wcnt, *_bw += _wcnt, _btw -= _wcnt) {
		if ((_fp->fptr % SS(_fp->fs)) == 0) {	/* On the sector boundary? */
			_csect = (BYTE)(_fp->fptr / SS(_fp->fs) & (_fp->fs->csize - 1));	/* Sector offset in the cluster */
			if (!_csect) {					/* On the cluster boundary? */
				if (_fp->fptr == 0) {		/* On the top of the file? */
					_clst = _fp->sclust;		/* Follow from the origin */
					if (_clst == 0)			/* When no cluster is allocated, */
						_fp->sclust = _clst = create_chain(_fp->fs, 0);	/* Create a new cluster chain */
				}
				else {					/* Middle or end of the file */
					#if _USE_FASTSEEK
						if (_fp->cltbl)
							_clst = clmt_clust(_fp, _fp->fptr);	/* Get cluster# from the CLMT */
						else
					#endif
							_clst = create_chain(_fp->fs, _fp->clust);	/* Follow or stretch cluster chain on the FAT */
				}
				if (_clst == 0) break;		/* Could not allocate a new cluster (disk full) */
				if (_clst == 1) {
					ABORT(_fp->fs, FR_INT_ERR);
				}
				if (_clst == 0xFFFFFFFF) {
					ABORT(_fp->fs, FR_DISK_ERR);
				}
				_fp->clust = _clst;			/* Update current cluster */
			}
			#if _FS_TINY
				if (_fp->fs->winsect == _fp->dsect && sync_window(_fp->fs))	{ /* Write-back sector cache */
					ABORT(_fp->fs, FR_DISK_ERR);
				}
			#else
				if (_fp->flag & FA__DIRTY) {		/* Write-back sector cache */
					_io_status = disk_write(_fp->fs->drv, _fp->buf, _fp->dsect, 1);
					if (_io_status != RES_OK) {
						ABORT(_fp->fs, FR_DISK_ERR);
					}
					_fp->flag &= ~FA__DIRTY;
				}
			#endif
			_sect = clust2sect(_fp->fs, _fp->clust);	/* Get current sector */
			if (!_sect) {
				ABORT(_fp->fs, FR_INT_ERR);
			}
			_sect += _csect;
			_cc = _btw / SS(_fp->fs);			/* When remaining bytes >= sector size, */
			if (_cc) {						/* Write maximum contiguous sectors directly */
				if (_csect + _cc > _fp->fs->csize)	/* Clip at cluster boundary */
					_cc = _fp->fs->csize - _csect;
				
				_io_status = disk_write(_fp->fs->drv, _wbuff, _sect, (BYTE)_cc);
				if (_io_status != RES_OK) {
					ABORT(_fp->fs, FR_DISK_ERR);
				}
				
				#if _FS_TINY
					if (_fp->fs->winsect - _sect < _cc) {	/* Refill sector cache if it gets invalidated by the direct write */
						mem_cpy(_fp->fs->win, _wbuff + ((_fp->fs->winsect - _sect) * SS(_fp->fs)), SS(_fp->fs));
						_fp->fs->wflag = 0;
					}
				#else
					if (_fp->dsect - _sect < _cc) { /* Refill sector cache if it gets invalidated by the direct write */
						mem_cpy(_fp->buf, _wbuff + ((_fp->dsect - _sect) * SS(_fp->fs)), SS(_fp->fs));
						_fp->flag &= ~FA__DIRTY;
					}
				#endif
				_wcnt = SS(_fp->fs) * _cc;		/* Number of bytes transferred */
				continue;
			}
			#if _FS_TINY
				if (_fp->fptr >= _fp->fsize) {	/* Avoid silly cache filling at growing edge */
					_res = sync_window(_fp->fs);
					if (_res) {
						ABORT(_fp->fs, FR_DISK_ERR);
					}
					_fp->fs->winsect = _sect;
				}
			#else
				if (_fp->dsect != _sect) {		/* Fill sector cache with file data */
					_io_status = disk_read(_fp->fs->drv, _fp->buf, _sect, 1);
					if (_fp->fptr < _fp->fsize && _io_status != RES_OK) {
						ABORT(_fp->fs, FR_DISK_ERR);
					}
				}
			#endif
			_fp->dsect = _sect;
		}
		_wcnt = SS(_fp->fs) - ((UINT)_fp->fptr % SS(_fp->fs));/* Put partial sector into file I/O buffer */
		if (_wcnt > _btw) _wcnt = _btw;
		#if _FS_TINY
			_res = move_window(_fp->fs, _fp->dsect);	/* Move sector window */
			if (_res) {
				ABORT(_fp->fs, FR_DISK_ERR);
			}
			mem_cpy(&_fp->fs->win[_fp->fptr % SS(_fp->fs)], _wbuff, _wcnt);	/* Fit partial sector */
			_fp->fs->wflag = 1;
		#else
			mem_cpy(&_fp->buf[_fp->fptr % SS(_fp->fs)], _wbuff, _wcnt);	/* Fit partial sector */
			_fp->flag |= FA__DIRTY;
		#endif
	}

	if (_fp->fptr > _fp->fsize) _fp->fsize = _fp->fptr;	/* Update file size if needed */
	_fp->flag |= FA__WRITTEN;						/* Set file change flag */

	unlock_fs(_fp->fs, FR_OK);
	return FR_OK;
}


FRESULT f_sync(FIL *_fp)
{
	FRESULT _res;
	DWORD _tm;
	BYTE *_dir;


	_res = validate(_fp);					/* Check validity of the object */
	if (_res == FR_OK) {
		if (_fp->flag & FA__WRITTEN) {	/* Has the file been written? */
			#if !_FS_TINY	/* Write-back dirty buffer */
				if (_fp->flag & FA__DIRTY) {
					if (disk_write(_fp->fs->drv, _fp->buf, _fp->dsect, 1) != RES_OK)
						LEAVE_FF(_fp->fs, FR_DISK_ERR);
					_fp->flag &= ~FA__DIRTY;
				}
			#endif
			/* Update the directory entry */
			_res = move_window(_fp->fs, _fp->dir_sect);
			if (_res == FR_OK) {
				_dir = _fp->dir_ptr;
				_dir[DIR_Attr] |= AM_ARC;					/* Set archive bit */
				ST_DWORD(_dir + DIR_FileSize, _fp->fsize);		/* Update file size */
				st_clust(_dir, _fp->sclust);					/* Update start cluster */
				_tm = get_fattime();							/* Update updated time */
				ST_DWORD(_dir + DIR_WrtTime, _tm);
				ST_WORD(_dir + DIR_LstAccDate, 0);
				_fp->flag &= ~FA__WRITTEN;
				_fp->fs->wflag = 1;
				_res = sync_fs(_fp->fs);
			}
		}
	}

	unlock_fs(_fp->fs, _res);
	return _res;
}

#endif /* !_FS_READONLY */


FRESULT f_close(FIL *_fp)
{
	FRESULT _res;


	#if _FS_READONLY
		_res = validate(_fp);
		{
		#if _FS_REENTRANT
			FATFS *_fs = _fp->fs;
		#endif
			if (_res == FR_OK) _fp->fs = 0;	/* Discard file object */
			LEAVE_FF(_fs, _res);
		}
	#else
		_res = f_sync(_fp);		/* Flush cached data */
		#if _FS_LOCK
			if (_res == FR_OK) {		/* Decrement open counter */
				#if _FS_REENTRANT
					FATFS *_fs = _fp->fs;
					_res = validate(_fp);
					if (_res == FR_OK) {
						_res = dec_lock(_fp->lockid);	
						unlock_fs(_fs, FR_OK);
					}
				#else
					_res = dec_lock(_fp->lockid);
				#endif
			}
		#endif
			if (_res == FR_OK) _fp->fs = 0;	/* Discard file object */
				return _res;
		#endif
}




/*-----------------------------------------------------------------------*/
/* Current Drive/Directory Handling                                     */
/*-----------------------------------------------------------------------*/

#if _FS_RPATH >= 1

FRESULT f_chdrive(BYTE _drv)
{
	if (_drv >= _VOLUMES) return FR_INVALID_DRIVE;

	CurrVol = _drv;

	return FR_OK;
}


FRESULT f_chdir(const TCHAR *_path)
{
	FRESULT _res;
	DIR _dj;
	DEF_NAMEBUF;

	_res = chk_mounted(&_path, &_dj.fs, 0);

	FATFS_DEBUGF("Mount Res: %d\n", _res);

	if (_res == FR_OK) {
		INIT_BUF(_dj);
		/* Follow the path */
		_res = follow_path(&_dj, _path);
		FATFS_DEBUGF("Follow path Res: %d\n", _res);
		FREE_BUF();

		/* Follow completed */
		if (_res == FR_OK) {
			if (!_dj.dir) {
				/* Start directory itself */
				_dj.fs->cdir = _dj.sclust;
			}
			else {
				/* Reached to the directory */
				if (_dj.dir[DIR_Attr] & AM_DIR) {
					_dj.fs->cdir = ld_clust(_dj.fs, _dj.dir);
					FATFS_DEBUGF("This is directory\n");
				}
				else {
					/* Reached but a file */
					_res = FR_NO_PATH;
					FATFS_DEBUGF("This is file\n");
				}
			}
		}
		if (_res == FR_NO_FILE) _res = FR_NO_PATH;
	}

	unlock_fs(_dj.fs, _res);
	return _res;
}


#if _FS_RPATH >= 2

FRESULT f_getcwd(TCHAR *_buff, UINT _len)
{
	FRESULT _res;
	DIR _dj;
	UINT i, n;
	DWORD _ccl;
	TCHAR *_tp;
	FILINFO _fno;
	DEF_NAMEBUF;


	*_buff = 0;
	_res = chk_mounted((const TCHAR**)&_buff, &_dj.fs, 0);	/* Get current volume */
	if (_res == FR_OK) {
		INIT_BUF(_dj);
		i = _len;			/* Bottom of buffer (dir stack base) */
		_dj.sclust = _dj.fs->cdir;			/* Start to follow upper dir from current dir */
		while ((_ccl = _dj.sclust) != 0) {	/* Repeat while current dir is a sub-dir */
			_res = dir_sdi(&_dj, 1);			/* Get parent dir */
			if (_res != FR_OK) break;
			_res = dir_read(&_dj, 0);
			if (_res != FR_OK) break;
			_dj.sclust = ld_clust(_dj.fs, _dj.dir);	/* Goto parent dir */
			_res = dir_sdi(&_dj, 0);
			if (_res != FR_OK) break;
			do {							/* Find the entry links to the child dir */
				_res = dir_read(&_dj, 0);
				if (_res != FR_OK) break;
				if (_ccl == ld_clust(_dj.fs, _dj.dir)) break;	/* Found the entry */
				_res = dir_next(&_dj, 0);	
			} while (_res == FR_OK);
			if (_res == FR_NO_FILE) _res = FR_INT_ERR;/* It cannot be 'not found'. */
			if (_res != FR_OK) break;
			
			#if _USE_LFN
				_fno.lfname = _buff;
				_fno.lfsize = i;
			#endif
			
			get_fileinfo(&_dj, &_fno);		/* Get the dir name and push it to the buffer */
			_tp = _fno.fname;
			if (_USE_LFN && *_buff) _tp = _buff;
			for (n = 0; _tp[n]; n++) ;
			if (i < n + 3) {
				_res = FR_NOT_ENOUGH_CORE; break;
			}
			while (n) _buff[--i] = _tp[--n];
			_buff[--i] = '/';
		}
		_tp = _buff;
		if (_res == FR_OK) {
			*_tp++ = '0' + CurrVol;			/* Put drive number */
			*_tp++ = ':';
			if (i == _len) {					/* Root-dir */
				*_tp++ = '/';
			}
			else {						/* Sub-dir */
				do		/* Add stacked path str */
					*_tp++ = _buff[i++];
				while (i < _len);
			}
		}
		*_tp = 0;
		FREE_BUF();
	}

	unlock_fs(_dj.fs, _res);
	return _res;
}
#endif /* _FS_RPATH >= 2 */
#endif /* _FS_RPATH >= 1 */



#if _FS_MINIMIZE <= 2

FRESULT f_lseek(FIL *_fp, DWORD _ofs)
{
	FRESULT _res;


	_res = validate(_fp);					/* Check validity of the object */
	if (_res != FR_OK) LEAVE_FF(_fp->fs, _res);
	if (_fp->flag & FA__ERROR)			/* Check abort flag */
		LEAVE_FF(_fp->fs, FR_INT_ERR);

	#if _USE_FASTSEEK
		if (_fp->cltbl) {	/* Fast seek */
			DWORD _cl, _pcl, _ncl, _tcl, _dsc, _tlen, _ulen, *_tbl;
			
			if (_ofs == CREATE_LINKMAP) {	/* Create CLMT */
				_tbl = _fp->cltbl;
				_tlen = *_tbl++; _ulen = 2;	/* Given table size and required table size */
				_cl = _fp->sclust;			/* Top of the chain */
				if (_cl) {
					do {
						/* Get a fragment */
						_tcl = _cl; _ncl = 0; _ulen += 2;	/* Top, length and used items */
						do {
							_pcl = _cl; _ncl++;
							_cl = get_fat(_fp->fs, _cl);
							if (_cl <= 1) ABORT(_fp->fs, FR_INT_ERR);
							if (_cl == 0xFFFFFFFF) ABORT(_fp->fs, FR_DISK_ERR);
						} while (_cl == _pcl + 1);
						
						if (_ulen <= _tlen) {		/* Store the length and top of the fragment */
							*_tbl++ = _ncl; *_tbl++ = _tcl;
						}
					} while (_cl < _fp->fs->n_fatent);	/* Repeat until end of chain */
				}
				*_fp->cltbl = _ulen;	/* Number of items used */
				if (_ulen <= _tlen)
					*_tbl = 0;		/* Terminate table */
				else
					_res = FR_NOT_ENOUGH_CORE;	/* Given table size is smaller than required */
					
			}
			else {						/* Fast seek */
				if (_ofs > _fp->fsize)		/* Clip offset at the file size */
					_ofs = _fp->fsize;
				_fp->fptr = _ofs;				/* Set file pointer */
				if (_ofs) {
					_fp->clust = clmt_clust(_fp, _ofs - 1);
					_dsc = clust2sect(_fp->fs, _fp->clust);
					if (!_dsc) ABORT(_fp->fs, FR_INT_ERR);
					_dsc += (_ofs - 1) / SS(_fp->fs) & (_fp->fs->csize - 1);
					if (_fp->fptr % SS(_fp->fs) && _dsc != _fp->dsect) {	/* Refill sector cache if needed */
						
						#if !_FS_TINY
							#if !_FS_READONLY
								if (_fp->flag & FA__DIRTY) {		/* Write-back dirty sector cache */
									if (disk_write(_fp->fs->drv, _fp->buf, _fp->dsect, 1) != RES_OK)
										ABORT(_fp->fs, FR_DISK_ERR);
									_fp->flag &= ~FA__DIRTY;
								}
							#endif
							
							if (disk_read(_fp->fs->drv, _fp->buf, _dsc, 1) != RES_OK)	/* Load current sector */
								ABORT(_fp->fs, FR_DISK_ERR);
						#endif
						_fp->dsect = _dsc;
					}
				}
			}
		} else
	#endif /* _USE_FASTSEEK */

	/* Normal Seek */
	{
		DWORD _clst, _bcs, _nsect, _ifptr;

		if (_ofs > _fp->fsize					/* In read-only mode, clip offset with the file size */
			#if !_FS_READONLY
			 && !(_fp->flag & FA_WRITE)
			#endif
			) _ofs = _fp->fsize;

		_ifptr = _fp->fptr;
		_fp->fptr = _nsect = 0;
		if (_ofs) {
			_bcs = (DWORD)_fp->fs->csize * SS(_fp->fs);	/* Cluster size (byte) */
			if (_ifptr > 0 &&
				(_ofs - 1) / _bcs >= (_ifptr - 1) / _bcs) {	/* When seek to same or following cluster, */
				_fp->fptr = (_ifptr - 1) & ~(_bcs - 1);	/* start from the current cluster */
				_ofs -= _fp->fptr;
				_clst = _fp->clust;
			}
			else {									/* When seek to back cluster, */
				_clst = _fp->sclust;						/* start from the first cluster */
				#if !_FS_READONLY
					if (_clst == 0) {						/* If no cluster chain, create a new chain */
						_clst = create_chain(_fp->fs, 0);
						if (_clst == 1) ABORT(_fp->fs, FR_INT_ERR);
						if (_clst == 0xFFFFFFFF) ABORT(_fp->fs, FR_DISK_ERR);
						_fp->sclust = _clst;
					}
				#endif
				_fp->clust = _clst;
			}
			if (_clst != 0) {
				while (_ofs > _bcs) {						/* Cluster following loop */
					#if !_FS_READONLY
						if (_fp->flag & FA_WRITE) {			/* Check if in write mode or not */
							_clst = create_chain(_fp->fs, _clst);	/* Force stretch if in write mode */
							if (_clst == 0) {				/* When disk gets full, clip file size */
								_ofs = _bcs; break;
							}
						} else
					#endif
						_clst = get_fat(_fp->fs, _clst);	/* Follow cluster chain if not in write mode */
					
					if (_clst == 0xFFFFFFFF) ABORT(_fp->fs, FR_DISK_ERR);
					if (_clst <= 1 || _clst >= _fp->fs->n_fatent) ABORT(_fp->fs, FR_INT_ERR);
					_fp->clust = _clst;
					_fp->fptr += _bcs;
					_ofs -= _bcs;
				}
				_fp->fptr += _ofs;
				if (_ofs % SS(_fp->fs)) {
					_nsect = clust2sect(_fp->fs, _clst);	/* Current sector */
					if (!_nsect) ABORT(_fp->fs, FR_INT_ERR);
					_nsect += _ofs / SS(_fp->fs);
				}
			}
		}
		if (_fp->fptr % SS(_fp->fs) && _nsect != _fp->dsect) {	/* Fill sector cache if needed */
			#if !_FS_TINY
				#if !_FS_READONLY
					if (_fp->flag & FA__DIRTY) {			/* Write-back dirty sector cache */
						if (disk_write(_fp->fs->drv, _fp->buf, _fp->dsect, 1) != RES_OK)
							ABORT(_fp->fs, FR_DISK_ERR);
						_fp->flag &= ~FA__DIRTY;
					}
				#endif
				if (disk_read(_fp->fs->drv, _fp->buf, _nsect, 1) != RES_OK)	/* Fill sector cache */
				ABORT(_fp->fs, FR_DISK_ERR);
			#endif
			_fp->dsect = _nsect;
		}
		#if !_FS_READONLY
		if (_fp->fptr > _fp->fsize) {			/* Set file change flag if the file size is extended */
			_fp->fsize = _fp->fptr;
			_fp->flag |= FA__WRITTEN;
		}
		#endif
	}

	unlock_fs(_fp->fs, _res);
	return _res;
}



#if _FS_MINIMIZE <= 1

FRESULT f_opendir(DIR *_dj, const TCHAR *_path)
{
	FRESULT _res;
	FATFS *_fs;
	DEF_NAMEBUF;


	if (!_dj) return FR_INVALID_OBJECT;

	_res = chk_mounted(&_path, &_dj->fs, 0);
	_fs = _dj->fs;
	if (_res == FR_OK) {
		INIT_BUF(*_dj);
		_res = follow_path(_dj, _path);			/* Follow the path to the directory */
		FREE_BUF();
		if (_res == FR_OK) {						/* Follow completed */
			if (_dj->dir) {						/* It is not the root dir */
				if (_dj->dir[DIR_Attr] & AM_DIR) {	/* The object is a directory */
					_dj->sclust = ld_clust(_fs, _dj->dir);
				}
				else {						/* The object is not a directory */
					_res = FR_NO_PATH;
				}
			}
			if (_res == FR_OK) {
				_dj->id = _fs->id;
				_res = dir_sdi(_dj, 0);			/* Rewind dir */
			}
		}
		if (_res == FR_NO_FILE) _res = FR_NO_PATH;
		if (_res != FR_OK) _dj->fs = 0;			/* Invalidate the dir object if function failed */
	}
	else {
		_dj->fs = 0;
	}

	unlock_fs(_fs, _res);
	return _res;
}

FRESULT f_readdir(DIR *_dj, FILINFO *_fno)
{
	FRESULT _res;
	DEF_NAMEBUF;


	_res = validate(_dj);						/* Check validity of the object */
	if (_res == FR_OK) {
		if (!_fno) {
			_res = dir_sdi(_dj, 0);			/* Rewind the directory object */
		}
		else {
			INIT_BUF(*_dj);
			_res = dir_read(_dj, 0);			/* Read an item */
			if (_res == FR_NO_FILE) {		/* Reached end of dir */
				_dj->sect = 0;
				_res = FR_OK;
			}
			if (_res == FR_OK) {				/* A valid entry is found */
				get_fileinfo(_dj, _fno);		/* Get the object information */
				_res = dir_next(_dj, 0);		/* Increment index for next */
				if (_res == FR_NO_FILE) {
					_dj->sect = 0;
					_res = FR_OK;
				}
			}
			FREE_BUF();
		}
	}

	unlock_fs(_dj->fs, _res);
	return _res;
}



#if _FS_MINIMIZE == 0


FRESULT f_stat(const TCHAR *_path, FILINFO *_fno)
{
	FRESULT _res;
	DIR _dj;
	DEF_NAMEBUF;


	_res = chk_mounted(&_path, &_dj.fs, 0);
	if (_res == FR_OK) {
		INIT_BUF(_dj);
		_res = follow_path(&_dj, _path);	/* Follow the file path */
		if (_res == FR_OK) {				/* Follow completed */
			if (_dj.dir)		/* Found an object */
				get_fileinfo(&_dj, _fno);
			else			/* It is root dir */
				_res = FR_INVALID_NAME;
		}
		FREE_BUF();
	}

	unlock_fs(_dj.fs, _res);
	return _res;
}



#if !_FS_READONLY

FRESULT f_getfree(const TCHAR *_path, DWORD *_nclst, FATFS **_fatfs)
{
	FRESULT _res;
	FATFS *_fs;
	DWORD n, _clst, _sect, _stat;
	UINT i;
	BYTE _fat, *_p;


	/* Get drive number */
	_res = chk_mounted(&_path, _fatfs, 0);
	_fs = *_fatfs;
	if (_res == FR_OK) {
		/* If free_clust is valid, return it without full cluster scan */
		if (_fs->free_clust <= _fs->n_fatent - 2) {
			*_nclst = _fs->free_clust;
		}
		else {
			/* Get number of free clusters */
			_fat = _fs->fs_type;
			n = 0;
			if (_fat == FS_FAT12) {
				_clst = 2;
				do {
					_stat = get_fat(_fs, _clst);
					if (_stat == 0xFFFFFFFF) { _res = FR_DISK_ERR; break; }
					if (_stat == 1) { _res = FR_INT_ERR; break; }
					if (_stat == 0) n++;
				} while (++_clst < _fs->n_fatent);
			}
			else {
				_clst = _fs->n_fatent;
				_sect = _fs->fatbase;
				i = 0; _p = 0;
				do {
					if (!i) {
						_res = move_window(_fs, _sect++);
						if (_res != FR_OK) break;
						_p = _fs->win;
						i = SS(_fs);
					}
					if (_fat == FS_FAT16) {
						if (LD_WORD(_p) == 0) n++;
						_p += 2; i -= 2;
					}
					else {
						if ((LD_DWORD(_p) & 0x0FFFFFFF) == 0) n++;
						_p += 4; i -= 4;
					}
				} while (--_clst);
			}
			_fs->free_clust = n;
			if (_fat == FS_FAT32) _fs->fsi_flag = 1;
			*_nclst = n;
		}
	}

	unlock_fs(_fs, _res);
	return _res;
}


FRESULT f_truncate(FIL *_fp)
{
	FRESULT _res;
	DWORD _ncl;


	_res = validate(_fp);						/* Check validity of the object */
	if (_res == FR_OK) {
		if (_fp->flag & FA__ERROR) {			/* Check abort flag */
			_res = FR_INT_ERR;
		}
		else {
			if (!(_fp->flag & FA_WRITE))		/* Check access mode */
				_res = FR_DENIED;
		}
	}
	if (_res == FR_OK) {
		if (_fp->fsize > _fp->fptr) {
			_fp->fsize = _fp->fptr;	/* Set file size to current R/W point */
			_fp->flag |= FA__WRITTEN;
			if (_fp->fptr == 0) {	/* When set file size to zero, remove entire cluster chain */
				_res = remove_chain(_fp->fs, _fp->sclust);
				_fp->sclust = 0;
			}
			else {				/* When truncate a part of the file, remove remaining clusters */
				_ncl = get_fat(_fp->fs, _fp->clust);
				_res = FR_OK;
				if (_ncl == 0xFFFFFFFF) _res = FR_DISK_ERR;
				if (_ncl == 1) _res = FR_INT_ERR;
				if (_res == FR_OK && _ncl < _fp->fs->n_fatent) {
					_res = put_fat(_fp->fs, _fp->clust, 0x0FFFFFFF);
					if (_res == FR_OK) _res = remove_chain(_fp->fs, _ncl);
				}
			}
		}
		if (_res != FR_OK) _fp->flag |= FA__ERROR;
	}

	unlock_fs(_fp->fs, _res);
	return _res;
}


FRESULT f_unlink(const TCHAR *_path)
{
	FRESULT _res;
	DIR _dj, _sdj;
	BYTE *_dir;
	DWORD _dclst;
	DEF_NAMEBUF;


	_res = chk_mounted(&_path, &_dj.fs, 1);
	if (_res == FR_OK) {
		INIT_BUF(_dj);
		_res = follow_path(&_dj, _path);		/* Follow the file path */
		if (_FS_RPATH && _res == FR_OK && (_dj.fn[NS] & NS_DOT))
			_res = FR_INVALID_NAME;			/* Cannot remove dot entry */
		#if _FS_LOCK
			if (_res == FR_OK) _res = chk_lock(&_dj, 2);	/* Cannot remove open file */
		#endif
		if (_res == FR_OK) {					/* The object is accessible */
			_dir = _dj.dir;
			if (!_dir) {
				_res = FR_INVALID_NAME;		/* Cannot remove the start directory */
			}
			else {
				if (_dir[DIR_Attr] & AM_RDO)
					_res = FR_DENIED;		/* Cannot remove R/O object */
			}
			_dclst = ld_clust(_dj.fs, _dir);
			if (_res == FR_OK && (_dir[DIR_Attr] & AM_DIR)) {	/* Is it a sub-dir? */
				if (_dclst < 2) {
					_res = FR_INT_ERR;
				}
				else {
					mem_cpy(&_sdj, &_dj, sizeof (DIR));	/* Check if the sub-dir is empty or not */
					_sdj.sclust = _dclst;
					_res = dir_sdi(&_sdj, 2);		/* Exclude dot entries */
					if (_res == FR_OK) {
						_res = dir_read(&_sdj, 0);	/* Read an item */
						if (_res == FR_OK		/* Not empty dir */
							#if _FS_RPATH
							|| _dclst == _dj.fs->cdir	/* Current dir */
							#endif
							) _res = FR_DENIED;
						if (_res == FR_NO_FILE) _res = FR_OK;	/* Empty */
					}
				}
			}
			if (_res == FR_OK) {
				_res = dir_remove(&_dj);		/* Remove the directory entry */
				if (_res == FR_OK) {
					if (_dclst)				/* Remove the cluster chain if exist */
						_res = remove_chain(_dj.fs, _dclst);
					if (_res == FR_OK) _res = sync_fs(_dj.fs);
				}
			}
		}
		FREE_BUF();
	}

	unlock_fs(_dj.fs, _res);
	return _res;
}


FRESULT f_mkdir(const TCHAR *_path)
{
	FRESULT _res;
	DIR _dj;
	BYTE *_dir, n;
	DWORD _dsc, _dcl, _pcl, _tm = get_fattime();
	DEF_NAMEBUF;


	_res = chk_mounted(&_path, &_dj.fs, 1);
	if (_res == FR_OK) {
		INIT_BUF(_dj);
		_res = follow_path(&_dj, _path);		/* Follow the file path */
		if (_res == FR_OK) {					/* Any object with same name is already existing */
			_res = FR_EXIST;
		}
		if (_FS_RPATH && _res == FR_NO_FILE && (_dj.fn[NS] & NS_DOT)) {
			_res = FR_INVALID_NAME;
		}
		if (_res == FR_NO_FILE) {				/* Can create a new directory */
			_dcl = create_chain(_dj.fs, 0);		/* Allocate a cluster for the new directory table */
			_res = FR_OK;
			if (_dcl == 0) _res = FR_DENIED;		/* No space to allocate a new cluster */
			if (_dcl == 1) _res = FR_INT_ERR;
			if (_dcl == 0xFFFFFFFF) _res = FR_DISK_ERR;
			if (_res == FR_OK) {					/* Flush FAT */
				_res = sync_window(_dj.fs);
			}
			if (_res == FR_OK) {					/* Initialize the new directory table */
				_dsc = clust2sect(_dj.fs, _dcl);
				_dir = _dj.fs->win;
				mem_set(_dir, 0, SS(_dj.fs));
				mem_set(_dir + DIR_Name, ' ', 11);	/* Create "." entry */
				_dir[DIR_Name] = '.';
				_dir[DIR_Attr] = AM_DIR;
				ST_DWORD(_dir + DIR_WrtTime, _tm);
				st_clust(_dir, _dcl);
				mem_cpy(_dir + SZ_DIR, _dir, SZ_DIR); 	/* Create ".." entry */
				_dir[33] = '.'; _pcl = _dj.sclust;
				if (_dj.fs->fs_type == FS_FAT32 && _pcl == _dj.fs->dirbase)
					_pcl = 0;
				st_clust(_dir + SZ_DIR, _pcl);
				for (n = _dj.fs->csize; n; n--) {	/* Write dot entries and clear following sectors */
					_dj.fs->winsect = _dsc++;
					_dj.fs->wflag = 1;
					_res = sync_window(_dj.fs);
					if (_res != FR_OK) break;
					mem_set(_dir, 0, SS(_dj.fs));
				}
			}
			if (_res == FR_OK) {
				_res = dir_register(&_dj);	/* Register the object to the directory */
			}
			if (_res != FR_OK) {
				remove_chain(_dj.fs, _dcl);			/* Could not register, remove cluster chain */
			}
			else {
				_dir = _dj.dir;
				_dir[DIR_Attr] = AM_DIR;				/* Attribute */
				ST_DWORD(_dir + DIR_WrtTime, _tm);		/* Created time */
				st_clust(_dir, _dcl);					/* Table start cluster */
				_dj.fs->wflag = 1;
				_res = sync_fs(_dj.fs);
			}
		}
		FREE_BUF();
	}
	

	unlock_fs(_dj.fs, _res);
	return _res;
}


FRESULT f_chmod(const TCHAR *_path, BYTE _value, BYTE _mask)
{
	FRESULT _res;
	DIR _dj;
	BYTE *_dir;
	DEF_NAMEBUF;


	_res = chk_mounted(&_path, &_dj.fs, 1);
	if (_res == FR_OK) {
		INIT_BUF(_dj);
		_res = follow_path(&_dj, _path);		/* Follow the file path */
		FREE_BUF();
		if (_FS_RPATH && _res == FR_OK && (_dj.fn[NS] & NS_DOT))
			_res = FR_INVALID_NAME;
		if (_res == FR_OK) {
			_dir = _dj.dir;
			if (!_dir) {						/* Is it a root directory? */
				_res = FR_INVALID_NAME;
			}
			else {						/* File or sub directory */
				_mask &= AM_RDO|AM_HID|AM_SYS|AM_ARC;	/* Valid attribute mask */
				_dir[DIR_Attr] = (_value & _mask) | (_dir[DIR_Attr] & (BYTE)~_mask);	/* Apply attribute change */
				_dj.fs->wflag = 1;
				_res = sync_fs(_dj.fs);
			}
		}
	}

	unlock_fs(_dj.fs, _res);
	return _res;
}


FRESULT f_utime(const TCHAR *_path, const FILINFO *_fno)
{
	FRESULT _res;
	DIR _dj;
	BYTE *_dir;
	DEF_NAMEBUF;


	_res = chk_mounted(&_path, &_dj.fs, 1);
	if (_res == FR_OK) {
		INIT_BUF(_dj);
		_res = follow_path(&_dj, _path);	/* Follow the file path */
		FREE_BUF();
		if (_FS_RPATH && _res == FR_OK && (_dj.fn[NS] & NS_DOT))
			_res = FR_INVALID_NAME;
		if (_res == FR_OK) {
			_dir = _dj.dir;
			if (!_dir) {					/* Root directory */
				_res = FR_INVALID_NAME;
			}
			else {					/* File or sub-directory */
				ST_WORD(_dir + DIR_WrtTime, _fno->ftime);
				ST_WORD(_dir + DIR_WrtDate, _fno->fdate);
				_dj.fs->wflag = 1;
				_res = sync_fs(_dj.fs);
			}
		}
	}

	unlock_fs(_dj.fs, _res);
	return _res;
}


FRESULT f_rename(const TCHAR *_path_old, const TCHAR *_path_new)
{
	FRESULT _res;
	DIR _djo, _djn;
	BYTE _buf[21], *_dir;
	DWORD _dw;
	DEF_NAMEBUF;


	_res = chk_mounted(&_path_old, &_djo.fs, 1);
	if (_res == FR_OK) {
		_djn.fs = _djo.fs;
		INIT_BUF(_djo);
		_res = follow_path(&_djo, _path_old);		/* Check old object */
		if (_FS_RPATH && _res == FR_OK && (_djo.fn[NS] & NS_DOT))
			_res = FR_INVALID_NAME;
			#if _FS_LOCK
				if (_res == FR_OK) _res = chk_lock(&_djo, 2);
			#endif
			if (_res == FR_OK) {						/* Old object is found */
			if (!_djo.dir) {						/* Is root dir? */
				_res = FR_NO_FILE;
			}
			else {
				mem_cpy(_buf, _djo.dir + DIR_Attr, 21);		/* Save the object information except for name */
				mem_cpy(&_djn, &_djo, sizeof (DIR));		/* Check new object */
				_res = follow_path(&_djn, _path_new);
				if (_res == FR_OK) _res = FR_EXIST;		/* The new object name is already existing */
				if (_res == FR_NO_FILE) { 				/* Is it a valid path and no name collision? */
					/* Start critical section that any interruption can cause a cross-link */
					_res = dir_register(&_djn);			/* Register the new entry */
					if (_res == FR_OK) {
						_dir = _djn.dir;					/* Copy object information except for name */
						mem_cpy(_dir + 13, _buf + 2, 19);
						_dir[DIR_Attr] = _buf[0] | AM_ARC;
						_djo.fs->wflag = 1;
						if (_djo.sclust != _djn.sclust && (_dir[DIR_Attr] & AM_DIR)) {		/* Update .. entry in the directory if needed */
							_dw = clust2sect(_djo.fs, ld_clust(_djo.fs, _dir));
							if (!_dw) {
								_res = FR_INT_ERR;
							}
							else {
								_res = move_window(_djo.fs, _dw);
								_dir = _djo.fs->win + SZ_DIR;	/* .. entry */
								if (_res == FR_OK && _dir[1] == '.') {
									_dw = (_djo.fs->fs_type == FS_FAT32 && _djn.sclust == _djo.fs->dirbase) ? 0 : _djn.sclust;
									st_clust(_dir, _dw);
									_djo.fs->wflag = 1;
								}
							}
						}
						if (_res == FR_OK) {
							_res = dir_remove(&_djo);		/* Remove old entry */
							if (_res == FR_OK)
								_res = sync_fs(_djo.fs);
						}
					}
					/* End critical section */
				}
			}
		}
		FREE_BUF();
	}

	unlock_fs(_djo.fs, _res);
	return _res;
}

#endif /* !_FS_READONLY */
#endif /* _FS_MINIMIZE == 0 */
#endif /* _FS_MINIMIZE <= 1 */
#endif /* _FS_MINIMIZE <= 2 */



#if _USE_LABEL

FRESULT f_getlabel(const TCHAR *_path, TCHAR *_label, DWORD *_sn)
{
	FRESULT _res;
	DIR _dj;
	UINT i, j;


	/* Get logical drive */
	_res = chk_mounted(&_path, &_dj.fs, 0);

	/* Get volume label */
	if (_res == FR_OK && _label) {
		_dj.sclust = 0;					/* Open root dir */
		_res = dir_sdi(&_dj, 0);
		if (_res == FR_OK) {
			_res = dir_read(&_dj, 1);		/* Get an entry with AM_VOL */
			if (_res == FR_OK) {			/* A volume label is exist */
				#if _LFN_UNICODE
					WCHAR _w;
					i = j = 0;
					do {
						_w = (i < 11) ? _dj.dir[i++] : ' ';
						if (IsDBCS1(_w) && i < 11 && IsDBCS2(_dj.dir[i]))
							_w = (_w << 8) | _dj.dir[i++];
						_label[j++] = ff_convert(_w, 1);
					} while (j < 11);
				#else
					mem_cpy(_label, _dj.dir, 11);
				#endif
				j = 11;
				do {
					_label[j] = 0;
					if (!j) break;
				} while (_label[--j] == ' ');
			}
			if (_res == FR_NO_FILE) {	/* No label, return nul string */
				_label[0] = 0;
				_res = FR_OK;
			}
		}
	}

	/* Get volume serial number */
	if (_res == FR_OK && _sn) {
		_res = move_window(_dj.fs, _dj.fs->volbase);
		if (_res == FR_OK) {
			i = _dj.fs->fs_type == FS_FAT32 ? BS_VolID32 : BS_VolID;
			*_sn = LD_DWORD(&_dj.fs->win[i]);
		}
	}

	unlock_fs(_dj.fs, _res);
	return _res;
}



#if !_FS_READONLY


FRESULT f_setlabel(const TCHAR *_label)
{
	FRESULT _res;
	DIR _dj;
	BYTE _vn[11];
	UINT i, j, _sl;
	WCHAR _w;
	DWORD _tm;


	/* Get logical drive */
	_res = chk_mounted(&_label, &_dj.fs, 1);
	if (_res) LEAVE_FF(_dj.fs, _res);

	/* Create a volume label in directory form */
	_vn[0] = 0;
	for (_sl = 0; _label[_sl]; _sl++) ;				/* Get name length */
	for ( ; _sl && _label[_sl-1] == ' '; _sl--) ;	/* Remove trailing spaces */
	if (_sl) {	/* Create volume label in directory form */
		i = j = 0;
		do {
			#if _LFN_UNICODE
				_w = ff_convert(ff_wtoupper(_label[i++]), 0);
			#else
				_w = (BYTE)_label[i++];
				if (IsDBCS1(_w))
				_w = (j < 10 && i < _sl && IsDBCS2(_label[i])) ? (_w << 8) | (BYTE)_label[i++] : 0;
				#if _USE_LFN
					_w = ff_convert(ff_wtoupper(ff_convert(_w, 1)), 0);
				#else
					if (IsLower(_w)) _w -= 0x20;			/* To upper ASCII chars */
					#ifdef _EXCVT
						if (_w >= 0x80) _w = ExCvt[_w - 0x80];	/* To upper extended chars (SBCS cfg) */
					#else
						if (!_DF1S && _w >= 0x80) _w = 0;		/* Reject extended chars (ASCII cfg) */
					#endif
				#endif
			#endif
			if (!_w || chk_chr("\"*+,.:;<=>\?[]|\x7F", _w) || j >= (UINT)((_w >= 0x100) ? 10 : 11)) /* Reject invalid chars for volume label */
				LEAVE_FF(_dj.fs, FR_INVALID_NAME);
			if (_w >= 0x100) _vn[j++] = (BYTE)(_w >> 8);
			_vn[j++] = (BYTE)_w;
		} while (i < _sl);
		while (j < 11) _vn[j++] = ' ';
	}

	/* Set volume label */
	_dj.sclust = 0;					/* Open root dir */
	_res = dir_sdi(&_dj, 0);
	if (_res == FR_OK) {
		_res = dir_read(&_dj, 1);		/* Get an entry with AM_VOL */
		if (_res == FR_OK) {			/* A volume label is found */
			if (_vn[0]) {
				mem_cpy(_dj.dir, _vn, 11);	/* Change the volume label name */
				_tm = get_fattime();
				ST_DWORD(_dj.dir+DIR_WrtTime, _tm);
			}
			else {
				_dj.dir[0] = DDE;			/* Remove the volume label */
			}
			_dj.fs->wflag = 1;
			_res = sync_fs(_dj.fs);
		}
		else {					/* No volume label is found or error */
			if (_res == FR_NO_FILE) {
				_res = FR_OK;
				if (_vn[0]) {				/* Create volume label as new */
					_res = dir_alloc(&_dj, 1);	/* Allocate an entry for volume label */
					if (_res == FR_OK) {
						mem_set(_dj.dir, 0, SZ_DIR);	/* Set volume label */
						mem_cpy(_dj.dir, _vn, 11);
						_dj.dir[DIR_Attr] = AM_VOL;
						_tm = get_fattime();
						ST_DWORD(_dj.dir+DIR_WrtTime, _tm);
						_dj.fs->wflag = 1;
						_res = sync_fs(_dj.fs);
					}
				}
			}
		}
	}

	unlock_fs(_dj.fs, _res);
	return _res;
}

#endif /* !_FS_READONLY */
#endif /* _USE_LABEL */


#if _USE_FORWARD && _FS_TINY

FRESULT f_forward(FIL *_fp, UINT (*func)(const BYTE*,UINT), UINT _btf, UINT *_bf)
{
	FRESULT _res;
	DWORD _remain, _clst, _sect;
	UINT _rcnt;
	BYTE _csect;


	*_bf = 0;	/* Clear transfer byte counter */

	_res = validate(_fp);							/* Check validity of the object */
	if (_res != FR_OK) LEAVE_FF(_fp->fs, _res);
	if (_fp->flag & FA__ERROR)						/* Check error flag */
		LEAVE_FF(_fp->fs, FR_INT_ERR);
	if (!(_fp->flag & FA_READ))						/* Check access mode */
		LEAVE_FF(_fp->fs, FR_DENIED);

	_remain = _fp->fsize - _fp->fptr;
	if (_btf > _remain) _btf = (UINT)_remain;			/* Truncate btf by remaining bytes */

	for ( ;  _btf && (*func)(0, 0);					/* Repeat until all data transferred or stream becomes busy */
		_fp->fptr += _rcnt, *_bf += _rcnt, _btf -= _rcnt) {
		_csect = (BYTE)(_fp->fptr / SS(_fp->fs) & (_fp->fs->csize - 1));	/* Sector offset in the cluster */
		if ((_fp->fptr % SS(_fp->fs)) == 0) {			/* On the sector boundary? */
			if (!_csect) {							/* On the cluster boundary? */
				_clst = (_fp->fptr == 0) ?			/* On the top of the file? */
					_fp->sclust : get_fat(_fp->fs, _fp->clust);
				if (_clst <= 1) ABORT(_fp->fs, FR_INT_ERR);
				if (_clst == 0xFFFFFFFF) ABORT(_fp->fs, FR_DISK_ERR);
				_fp->clust = _clst;					/* Update current cluster */
			}
		}
		_sect = clust2sect(_fp->fs, _fp->clust);		/* Get current data sector */
		if (!_sect) ABORT(_fp->fs, FR_INT_ERR);
		_sect += _csect;
		if (move_window(_fp->fs, _sect))				/* Move sector window */
			ABORT(_fp->fs, FR_DISK_ERR);
		_fp->dsect = _sect;
		_rcnt = SS(fp->fs) - (WORD)(_fp->fptr % SS(_fp->fs));	/* Forward data from sector window */
		if (_rcnt > _btf) _rcnt = _btf;
		_rcnt = (*func)(&_fp->fs->win[(WORD)_fp->fptr % SS(_fp->fs)], _rcnt);
		if (!_rcnt) ABORT(_fp->fs, FR_INT_ERR);
	}

	LEAVE_FF(_fp->fs, FR_OK);
}
#endif /* _USE_FORWARD */



#if _USE_MKFS && !_FS_READONLY

#define N_ROOTDIR	512		/* Number of root dir entries for FAT12/16 */
#define N_FATS		1		/* Number of FAT copies (1 or 2) */


FRESULT f_mkfs(BYTE _vol, BYTE _sfd, UINT _au)
{
	static const WORD _vst[] = { 1024,   512,  256,  128,   64,    32,   16,    8,    4,    2,   0};
	static const WORD _cst[] = {32768, 16384, 8192, 4096, 2048, 16384, 8192, 4096, 2048, 1024, 512};
	BYTE _fmt, _md, _sys, *_tbl, _pdrv, _part;
	DWORD _n_clst, _vs, n, _wsect;
	UINT i;
	DWORD _b_vol, _b_fat, _b_dir, _b_data;	/* LBA */
	DWORD _n_vol, _n_rsv, _n_fat, _n_dir;	/* Size */
	FATFS *_fs;
	DSTATUS _stat;
	DRESULT _io_status;


	/* Check mounted drive and clear work area */
	if (_vol >= _VOLUMES) {
		return FR_INVALID_DRIVE;
	}
	if (_sfd > 1) {
		return FR_INVALID_PARAMETER;
	}
	if (_au & (_au - 1)) {
		return FR_INVALID_PARAMETER;
	}
	_fs = FatFs[_vol];
	if (!_fs) {
		return FR_NOT_ENABLED;
	}
	_fs->fs_type = 0;
	_pdrv = LD2PD(_vol);	/* Physical drive */
	_part = LD2PT(_vol);	/* Partition (0:auto detect, 1-4:get from partition table)*/

	/* Get disk statics */
	_stat = disk_initialize(_pdrv);
	if (_stat & STA_NOINIT) {
		return FR_NOT_READY;
	}
	if (_stat & STA_PROTECT) {
		return FR_WRITE_PROTECTED;
	}
	
	#if _MAX_SS != 512					/* Get disk sector size */
		_io_status = disk_ioctl(_pdrv, GET_SECTOR_SIZE, &SS(_fs));
		if (_io_status != RES_OK || SS(_fs) > _MAX_SS) {
			return FR_DISK_ERR;
		}
	#endif
	
	if (_MULTI_PARTITION && _part) {
		/* Get partition information from partition table in the MBR */
		_io_status = disk_read(_pdrv, _fs->win, 0, 1);
		if (_io_status != RES_OK) {
			return FR_DISK_ERR;
		}
		if (LD_WORD(_fs->win + BS_55AA) != 0xAA55) {
			return FR_MKFS_ABORTED;
		}
		_tbl = &_fs->win[MBR_Table + (_part - 1) * SZ_PTE];
		if (!_tbl[4]) {
			return FR_MKFS_ABORTED;	/* No partition? */
		}
		_b_vol = LD_DWORD(_tbl + 8);	/* Volume start sector */
		_n_vol = LD_DWORD(_tbl + 12);	/* Volume size */
	}
	else {
		/* Create a partition in this function */
		_io_status = disk_ioctl(_pdrv, GET_SECTOR_COUNT, &_n_vol);
		if (_io_status != RES_OK || _n_vol < 128) {
			return FR_DISK_ERR;
		}
		_b_vol = (_sfd) ? 0 : 63;		/* Volume start sector */
		_n_vol -= _b_vol;				/* Volume size */
	}

	if (!_au) {				/* AU auto selection */
		_vs = _n_vol / (2000 / (SS(_fs) / 512));
		for (i = 0; _vs < _vst[i]; i++) ;
		_au = _cst[i];
	}
	_au /= SS(_fs);		/* Number of sectors per cluster */
	if (_au == 0) _au = 1;
	if (_au > 128) _au = 128;

	/* Pre-compute number of clusters and FAT sub-type */
	_n_clst = _n_vol / _au;
	_fmt = FS_FAT12;
	if (_n_clst >= MIN_FAT16) _fmt = FS_FAT16;
	if (_n_clst >= MIN_FAT32) _fmt = FS_FAT32;

	/* Determine offset and size of FAT structure */
	if (_fmt == FS_FAT32) {
		_n_fat = ((_n_clst * 4) + 8 + SS(_fs) - 1) / SS(_fs);
		_n_rsv = 32;
		_n_dir = 0;
	}
	else {
		_n_fat = (_fmt == FS_FAT12) ? (_n_clst * 3 + 1) / 2 + 3 : (_n_clst * 2) + 4;
		_n_fat = (_n_fat + SS(_fs) - 1) / SS(_fs);
		_n_rsv = 1;
		_n_dir = (DWORD)N_ROOTDIR * SZ_DIR / SS(_fs);
	}
	_b_fat = _b_vol + _n_rsv;				/* FAT area start sector */
	_b_dir = _b_fat + _n_fat * N_FATS;		/* Directory area start sector */
	_b_data = _b_dir + _n_dir;				/* Data area start sector */
	if (_n_vol < _b_data + _au - _b_vol) {
		return FR_MKFS_ABORTED;				/* Too small volume */
	}

	/* Align data start sector to erase block boundary (for flash memory media) */
	if (disk_ioctl(_pdrv, GET_BLOCK_SIZE, &n) != RES_OK || !n || n > 32768) n = 1;
	n = (_b_data + n - 1) & ~(n - 1);	/* Next nearest erase block from current data start */
	n = (n - _b_data) / N_FATS;
	if (_fmt == FS_FAT32) {		/* FAT32: Move FAT offset */
		_n_rsv += n;
		_b_fat += n;
	}
	else {					/* FAT12/16: Expand FAT size */
		_n_fat += n;
	}

	/* Determine number of clusters and final check of validity of the FAT sub-type */
	_n_clst = (_n_vol - _n_rsv - _n_fat * N_FATS - _n_dir) / _au;
	if (   (_fmt == FS_FAT16 && _n_clst < MIN_FAT16)
		|| (_fmt == FS_FAT32 && _n_clst < MIN_FAT32))
		return FR_MKFS_ABORTED;

	switch (_fmt) {	/* Determine system ID for partition table */
	case FS_FAT12:	_sys = 0x01; break;
	case FS_FAT16:	_sys = (_n_vol < 0x10000) ? 0x04 : 0x06; break;
	default: 		_sys = 0x0C;
	}

	if (_MULTI_PARTITION && _part) {
		/* Update system ID in the partition table */
		_tbl = &_fs->win[MBR_Table + (_part - 1) * SZ_PTE];
		_tbl[4] = _sys;
		_io_status = disk_write(_pdrv, _fs->win, 0, 1);
		if (_io_status != RES_OK) {
			return FR_DISK_ERR;
		}
		_md = 0xF8;
	}
	else {
		if (_sfd) {	/* No partition table (SFD) */
			_md = 0xF0;
		}
		else {	/* Create partition table (FDISK) */
			mem_set(_fs->win, 0, SS(_fs));
			_tbl = _fs->win + MBR_Table;		/* Create partition table for single partition in the drive */
			_tbl[1] = 1;						/* Partition start head */
			_tbl[2] = 1;						/* Partition start sector */
			_tbl[3] = 0;						/* Partition start cylinder */
			_tbl[4] = _sys;						/* System type */
			_tbl[5] = 254;						/* Partition end head */
			n = (_b_vol + _n_vol) / 63 / 255;
			_tbl[6] = (BYTE)((n >> 2) | 63);	/* Partition end sector */
			_tbl[7] = (BYTE)n;					/* End cylinder */
			ST_DWORD(_tbl + 8, 63);				/* Partition start in LBA */
			ST_DWORD(_tbl + 12, _n_vol);		/* Partition size in LBA */
			ST_WORD(_fs->win + BS_55AA, 0xAA55);	/* MBR signature */
			_io_status = disk_write(_pdrv, _fs->win, 0, 1);	/* Write it to the MBR sector */
			if (_io_status != RES_OK) {
				return FR_DISK_ERR;
			}
			_md = 0xF8;
		}
	}

	/* Create BPB in the VBR */
	_tbl = _fs->win;							/* Clear sector */
	mem_set(_tbl, 0, SS(_fs));
	mem_cpy(_tbl, "\xEB\xFE\x90" "MSDOS5.0", 11);/* Boot jump code, OEM name */
	i = SS(_fs);								/* Sector size */
	ST_WORD(_tbl + BPB_BytsPerSec, i);
	_tbl[BPB_SecPerClus] = (BYTE)_au;			/* Sectors per cluster */
	ST_WORD(_tbl + BPB_RsvdSecCnt, _n_rsv);		/* Reserved sectors */
	_tbl[BPB_NumFATs] = N_FATS;				/* Number of FATs */
	i = (_fmt == FS_FAT32) ? 0 : N_ROOTDIR;	/* Number of rootdir entries */
	ST_WORD(_tbl + BPB_RootEntCnt, i);
	if (_n_vol < 0x10000) {					/* Number of total sectors */
		ST_WORD(_tbl + BPB_TotSec16, _n_vol);
	} else {
		ST_DWORD(_tbl + BPB_TotSec32, _n_vol);
	}
	_tbl[BPB_Media] = _md;					/* Media descriptor */
	ST_WORD(_tbl + BPB_SecPerTrk, 63);			/* Number of sectors per track */
	ST_WORD(_tbl + BPB_NumHeads, 255);			/* Number of heads */
	ST_DWORD(_tbl + BPB_HiddSec, _b_vol);		/* Hidden sectors */
	n = get_fattime();						/* Use current time as VSN */
	if (_fmt == FS_FAT32) {
		ST_DWORD(_tbl + BS_VolID32, n);		/* VSN */
		ST_DWORD(_tbl + BPB_FATSz32, _n_fat);	/* Number of sectors per FAT */
		ST_DWORD(_tbl + BPB_RootClus, 2);		/* Root directory start cluster (2) */
		ST_WORD(_tbl + BPB_FSInfo, 1);			/* FSInfo record offset (VBR+1) */
		ST_WORD(_tbl + BPB_BkBootSec, 6);		/* Backup boot record offset (VBR+6) */
		_tbl[BS_DrvNum32] = 0x80;			/* Drive number */
		_tbl[BS_BootSig32] = 0x29;			/* Extended boot signature */
		mem_cpy(_tbl + BS_VolLab32, "NO NAME    " "FAT32   ", 19);	/* Volume label, FAT signature */
	}
	else {
		ST_DWORD(_tbl + BS_VolID, n);			/* VSN */
		ST_WORD(_tbl + BPB_FATSz16, _n_fat);	/* Number of sectors per FAT */
		_tbl[BS_DrvNum] = 0x80;				/* Drive number */
		_tbl[BS_BootSig] = 0x29;				/* Extended boot signature */
		mem_cpy(_tbl + BS_VolLab, "NO NAME    " "FAT     ", 19);	/* Volume label, FAT signature */
	}
	ST_WORD(_tbl + BS_55AA, 0xAA55);			/* Signature (Offset is fixed here regardless of sector size) */
	_io_status = disk_write(_pdrv, _tbl, _b_vol, 1); /* Write it to the VBR sector */
	if (_io_status != RES_OK) {
		return FR_DISK_ERR;
	}
	if (_fmt == FS_FAT32) {							/* Write backup VBR if needed (VBR+6) */
		_io_status = disk_write(_pdrv, _tbl, _b_vol + 6, 1);
		if (_io_status != RES_OK) {
			return FR_DISK_ERR;
		}
	}

	/* Initialize FAT area */
	_wsect = _b_fat;
	for (i = 0; i < N_FATS; i++) {		/* Initialize each FAT copy */
		mem_set(_tbl, 0, SS(_fs));			/* 1st sector of the FAT  */
		n = _md;								/* Media descriptor byte */
		if (_fmt != FS_FAT32) {
			n |= (_fmt == FS_FAT12) ? 0x00FFFF00 : 0xFFFFFF00;
			ST_DWORD(_tbl + 0, n);				/* Reserve cluster #0-1 (FAT12/16) */
		} else {
			n |= 0xFFFFFF00;
			ST_DWORD(_tbl + 0, n);				/* Reserve cluster #0-1 (FAT32) */
			ST_DWORD(_tbl + 4, 0xFFFFFFFF);
			ST_DWORD(_tbl + 8, 0x0FFFFFFF);	/* Reserve cluster #2 for root dir */
		}
		
		_io_status = disk_write(_pdrv, _tbl, _wsect++, 1);
		if (_io_status != RES_OK) {
			return FR_DISK_ERR;
		}
		mem_set(_tbl, 0, SS(_fs));			/* Fill following FAT entries with zero */
		for (n = 1; n < _n_fat; n++) {		/* This loop may take a time on FAT32 volume due to many single sector writes */
			_io_status = disk_write(_pdrv, _tbl, _wsect++, 1);
			if (_io_status != RES_OK) {
				return FR_DISK_ERR;
			}
		}
	}

	/* Initialize root directory */
	i = (_fmt == FS_FAT32) ? _au : _n_dir;
	do {
		_io_status = disk_write(_pdrv, _tbl, _wsect++, 1);
		if (_io_status != RES_OK) {
			return FR_DISK_ERR;
		}
	} while (--i);

#if _USE_ERASE	/* Erase data area if needed */
	{
		DWORD _eb[2];

		_eb[0] = _wsect; _eb[1] = _wsect + (_n_clst - ((_fmt == FS_FAT32) ? 1 : 0)) * _au - 1;
		_io_status = disk_ioctl(_pdrv, CTRL_ERASE_SECTOR, _eb);
		if (_io_status != RES_OK) {
			return FR_DISK_ERR;
		}		
	}
#endif

	/* Create FSInfo if needed */
	if (_fmt == FS_FAT32) {
		ST_DWORD(_tbl + FSI_LeadSig, 0x41615252);
		ST_DWORD(_tbl + FSI_StrucSig, 0x61417272);
		ST_DWORD(_tbl + FSI_Free_Count, _n_clst - 1);	/* Number of free clusters */
		ST_DWORD(_tbl + FSI_Nxt_Free, 2);				/* Last allocated cluster# */
		ST_WORD(_tbl + BS_55AA, 0xAA55);
		_io_status = disk_write(_pdrv, _tbl, _b_vol + 1, 1);	/* Write original (VBR+1) */
		if (_io_status != RES_OK) {
			return FR_DISK_ERR;
		}
		
		_io_status = disk_write(_pdrv, _tbl, _b_vol + 7, 1);	/* Write backup (VBR+7) */
		if (_io_status != RES_OK) {
			return FR_DISK_ERR;
		}
	}

	_io_status = disk_ioctl(_pdrv, CTRL_SYNC, 0);
	
	return (_io_status == RES_OK) ? FR_OK : FR_DISK_ERR;
}


#if _MULTI_PARTITION

FRESULT f_fdisk(BYTE _pdrv, const DWORD _szt[], void *_work)
{
	UINT i, n, _sz_cyl, _tot_cyl, _b_cyl, _e_cyl, _p_cyl;
	BYTE _s_hd, _e_hd, *_p, *_buf = (BYTE*)_work;
	DSTATUS _stat;
	DRESULT _io_status;
	DWORD _sz_disk, _sz_part, _s_part;


	_stat = disk_initialize(_pdrv);
	if (_stat & STA_NOINIT) {
		return FR_NOT_READY;
	}
	if (_stat & STA_PROTECT) {
		return FR_WRITE_PROTECTED;
	}
	
	_io_status = disk_ioctl(_pdrv, GET_SECTOR_COUNT, &_sz_disk);
	if (_io_status != RES_OK) {
		return FR_DISK_ERR;
	}

	/* Determine CHS in the table regardless of the drive geometry */
	for (n = 16; n < 256 && _sz_disk / n / 63 > 1024; n *= 2) ;
	if (n == 256) n--;
	_e_hd = n - 1;
	_sz_cyl = 63 * n;
	_tot_cyl = _sz_disk / _sz_cyl;

	/* Create partition table */
	mem_set(_buf, 0, _MAX_SS);
	_p = _buf + MBR_Table; _b_cyl = 0;
	for (i = 0; i < 4; i++, _p += SZ_PTE) {
		_p_cyl = (_szt[i] <= 100) ? (DWORD)_tot_cyl * _szt[i] / 100 : _szt[i] / _sz_cyl;
		if (!_p_cyl) continue;
		_s_part = (DWORD)_sz_cyl * _b_cyl;
		_sz_part = (DWORD)_sz_cyl * _p_cyl;
		if (i == 0) {	/* Exclude first track of cylinder 0 */
			_s_hd = 1;
			_s_part += 63;
			_sz_part -= 63;
		}
		else {
			_s_hd = 0;
		}
		_e_cyl = _b_cyl + _p_cyl - 1;
		if (_e_cyl >= _tot_cyl) {
			return FR_INVALID_PARAMETER;
		}

		/* Set partition table */
		_p[1] = _s_hd;						/* Start head */
		_p[2] = (BYTE)((_b_cyl >> 2) + 1);	/* Start sector */
		_p[3] = (BYTE)_b_cyl;				/* Start cylinder */
		_p[4] = 0x06;						/* System type (temporary setting) */
		_p[5] = _e_hd;						/* End head */
		_p[6] = (BYTE)((_e_cyl >> 2) + 63);	/* End sector */
		_p[7] = (BYTE)_e_cyl;				/* End cylinder */
		ST_DWORD(_p + 8, _s_part);			/* Start sector in LBA */
		ST_DWORD(_p + 12, _sz_part);		/* Partition size */

		/* Next partition */
		_b_cyl += _p_cyl;
	}
	ST_WORD(_p, 0xAA55);

	/* Write it to the MBR */
	return (disk_write(_pdrv, _buf, 0, 1) || disk_ioctl(_pdrv, CTRL_SYNC, 0)) ? FR_DISK_ERR : FR_OK;
}


#endif /* _MULTI_PARTITION */
#endif /* _USE_MKFS && !_FS_READONLY */




#if _USE_STRFUNC

TCHAR *f_gets(TCHAR *_buff, int _len, FIL *_fp)
{
	int n = 0;
	TCHAR _c, *_p = _buff;
	BYTE _s[2];
	UINT _rc;


	while (n < _len - 1) {			/* Read bytes until buffer gets filled */
		f_read(_fp, _s, 1, &_rc);
		if (_rc != 1) break;			/* Break on EOF or error */
		_c = _s[0];
		#if _LFN_UNICODE					/* Read a character in UTF-8 encoding */
			if (_c >= 0x80) {
				if (_c < 0xC0) continue;	/* Skip stray trailer */
				if (_c < 0xE0) {			/* Two-byte sequence */
					f_read(_fp, _s, 1, &_rc);
					if (_rc != 1) break;
					_c = ((_c & 0x1F) << 6) | (_s[0] & 0x3F);
					if (_c < 0x80) _c = '?';
				}
				else {
					if (_c < 0xF0) {		/* Three-byte sequence */
						f_read(_fp, _s, 2, &_rc);
						if (_rc != 2) break;
						_c = (_c << 12) | ((_s[0] & 0x3F) << 6) | (_s[1] & 0x3F);
						if (_c < 0x800) _c = '?';
					}
					else {			/* Reject four-byte sequence */
						_c = '?';
					}
				}
			}
		#endif /* _LFN_UNICODE */
		
		#if _USE_STRFUNC >= 2
			if (_c == '\r') continue;	/* Strip '\r' */
		#endif
		*_p++ = _c;
		n++;
		if (_c == '\n') break;		/* Break on EOL */
	}
	*_p = 0;
	return n ? _buff : 0;			/* When no data read (eof or error), return with error. */
}



#if !_FS_READONLY
#include <stdarg.h>

int f_putc(TCHAR _c, FIL *_fp)
{
	UINT _bw, _btw;
	BYTE _s[3];


	#if _USE_STRFUNC >= 2
		if (_c == '\n') f_putc ('\r', _fp);	/* LF -> CRLF conversion */
	#endif

	#if _LFN_UNICODE	/* Write the character in UTF-8 encoding */
		if (_c < 0x80) {			/* 7-bit */
			_s[0] = (BYTE)_c;
			_btw = 1;
		}
		else {
			if (_c < 0x800) {	/* 11-bit */
				_s[0] = (BYTE)(0xC0 | (_c >> 6));
				_s[1] = (BYTE)(0x80 | (_c & 0x3F));
				_btw = 2;
			}
			else {			/* 16-bit */
				_s[0] = (BYTE)(0xE0 | (_c >> 12));
				_s[1] = (BYTE)(0x80 | ((_c >> 6) & 0x3F));
				_s[2] = (BYTE)(0x80 | (_c & 0x3F));
				_btw = 3;
			}
		}
	#else	/* Write the character without conversion */
		_s[0] = (BYTE)_c;
		_btw = 1;
	#endif
	
	f_write(_fp, _s, _btw, &_bw);		/* Write the char to the file */
	return (_bw == _btw) ? 1 : EOF;	/* Return the result */
}


int f_puts(const TCHAR *_str, FIL *_fp)
{
	int n;


	for (n = 0; *_str; _str++, n++) {
		if (f_putc(*_str, _fp) == EOF) return EOF;
	}
	return n;
}


int f_printf(FIL *_fp, const TCHAR *_str, ...)
{
	va_list _arp;
	BYTE _f, _r;
	UINT i, j, w;
	ULONG _v;
	TCHAR _c, _d, _s[16], *_p;
	int _res, _chc, _cc;


	va_start(_arp, _str);

	for (_cc = _res = 0; _cc != EOF; _res += _cc) {
		_c = *_str++;
		if (_c == 0) break;			/* End of string */
		if (_c != '%') {				/* Non escape character */
			_cc = f_putc(_c, _fp);
			if (_cc != EOF) _cc = 1;
			continue;
		}
		w = _f = 0;
		_c = *_str++;
		if (_c == '0') {				/* Flag: '0' padding */
			_f = 1; _c = *_str++;
		}
		else {
			if (_c == '-') {			/* Flag: left justified */
				_f = 2; _c = *_str++;
			}
		}
		while (IsDigit(_c)) {		/* Precision */
			w = w * 10 + _c - '0';
			_c = *_str++;
		}
		if (_c == 'l' || _c == 'L') {	/* Prefix: Size is long int */
			_f |= 4; _c = *_str++;
		}
		if (!_c) break;
		_d = _c;
		if (IsLower(_d)) _d -= 0x20;
		switch (_d) {				/* Type is... */
		case 'S' :					/* String */
			_p = va_arg(_arp, TCHAR*);
			for (j = 0; _p[j]; j++) ;
			_chc = 0;
			if (!(_f & 2)) {
				while (j++ < w) _chc += (_cc = f_putc(' ', _fp));
			}
			_chc += (_cc = f_puts(_p, _fp));
			while (j++ < w) _chc += (_cc = f_putc(' ', _fp));
			if (_cc != EOF) _cc = _chc;
			continue;
		case 'C' :					/* Character */
			_cc = f_putc((TCHAR)va_arg(_arp, int), _fp); continue;
		case 'B' :					/* Binary */
			_r = 2; break;
		case 'O' :					/* Octal */
			_r = 8; break;
		case 'D' :					/* Signed decimal */
		case 'U' :					/* Unsigned decimal */
			_r = 10; break;
		case 'X' :					/* Hexdecimal */
			_r = 16; break;
		default:					/* Unknown type (pass-through) */
			_cc = f_putc(_c, _fp); continue;
		}

		/* Get an argument and put it in numeral */
		_v = (_f & 4) ? (ULONG)va_arg(_arp, long) : ((_d == 'D') ? (ULONG)(long)va_arg(_arp, int) : (ULONG)va_arg(_arp, unsigned int));
		if (_d == 'D' && (_v & 0x80000000)) {
			_v = 0 - _v;
			_f |= 8;
		}
		i = 0;
		do {
			_d = (TCHAR)(_v % _r); _v /= _r;
			if (_d > 9) _d += (_c == 'x') ? 0x27 : 0x07;
			_s[i++] = _d + '0';
		} while (_v && i < sizeof _s / sizeof _s[0]);
		if (_f & 8) _s[i++] = '-';
		j = i; _d = (_f & 1) ? '0' : ' ';
		_chc = 0;
		while (!(_f & 2) && j++ < w) _chc += (_cc = f_putc(_d, _fp));
		do _chc += (_cc = f_putc(_s[--i], _fp)); while(i);
		while (j++ < w) _chc += (_cc = f_putc(' ', _fp));
		if (_cc != EOF) _cc = _chc;
	}

	va_end(_arp);
	return (_cc == EOF) ? _cc : _res;
}

#endif /* !_FS_READONLY */
#endif /* _USE_STRFUNC */
